Beispiel #1
0
def test_note():
    parts = [stream.Part() for i in range(3)]
    # note1 = m21note.Note(pitch.Pitch("C4"), quarterLength=3/7)
    # note2 = m21note.Note(pitch.Pitch("C4"), quarterLength=3/7)
    # note3 = m21note.Note(pitch.Pitch("C4"), quarterLength=1/7)
    note1 = m21note.Note(pitch.Pitch("C4"))
    note2 = m21note.Note(pitch.Pitch("C4"))
    note3 = m21note.Note(pitch.Pitch("C4"))

    # sep = duration.Tuplet(7,4)
    # sep.setDurationType('16th')
    print(f"type !! {note1.duration.type}")

    # note1.duration.appendTuplet(duration.Tuplet(7,4, '16th'))
    note1.duration = duration.Duration(type='eighth', dots=1)
    note1.duration.appendTuplet(duration.Tuplet(7, 4, '16th'))

    # note2.duration.appendTuplet(duration.Tuplet(7,4, '16th'))
    note2.duration = duration.Duration(type='eighth', dots=1)
    note2.duration.appendTuplet(duration.Tuplet(7, 4, '16th'))

    # note3.duration.appendTuplet(duration.Tuplet(7,4, '16th'))
    note3.duration = duration.Duration(type='16th')
    note3.duration.appendTuplet(duration.Tuplet(7, 4, '16th'))

    # note2.duration.Tuplet(7,4)
    # note3.duration.Tuplet()
    parts[0].append(note1)
    parts[0].append(note2)
    parts[0].append(note3)
    parts.append(tempo.MetronomeMark(number=60))
    s = stream.Stream(parts)
    s.write("musicxml", "dur_test" + ".musicxml")
    return True
Beispiel #2
0
    def tupletFromTuplet(self, tupletElement):
        '''
        Returns a :class:`~music21.duration.Tuplet` object from a <tuplet> tag. 

        
        >>> ci = capella.fromCapellaXML.CapellaImporter()
        >>> tupletTag = ci.domElementFromText('<tuplet count="3"/>')
        >>> ci.tupletFromTuplet(tupletTag)    
        <music21.duration.Tuplet 3/2/eighth>
        
        does not handle 'tripartite' = True
        '''
        numerator = 1
        denominator = 1
        if 'count' in tupletElement._attrs:
            numerator = int(tupletElement._attrs['count'].value)
            denominator = 1
            while numerator > denominator * 2:
                denominator *= 2
        if 'prolong' in tupletElement._attrs and tupletElement._attrs[
                'count'].value == 'true':
            denominator *= 2

        if 'tripartite' in tupletElement._attrs:
            print(
                "WE DON'T HANDLE TRIPARTITE YET! Email the file and a pdf so I can figure it out"
            )

        tup = duration.Tuplet(numerator, denominator)
        return tup
Beispiel #3
0
 def test_inexpressible_hidden_rests_become_forward_tags(self):
     """Express hidden rests with inexpressible durations as <forward> tags."""
     m = stream.Measure()
     # 7 eighths in the space of 4 eighths, imported as 137/480
     # (137/480) * 7 = 1.9979, not 2.0
     # music21 filled gap with an inexpressible 0.0021 rest and couldn't export
     septuplet = note.Note(type='eighth')
     tuplet_obj = duration.Tuplet(7, 4, 'eighth')
     septuplet.duration.appendTuplet(tuplet_obj)
     septuplet.duration.linked = False
     septuplet.quarterLength = fractions.Fraction(137, 480)
     m.repeatAppend(septuplet, 7)
     # leave 0.0021 gap and do the same thing from 2.0 -> 3.9979
     m.repeatInsert(septuplet, [2.0])
     m.repeatAppend(septuplet, 6)
     m.insert(0, meter.TimeSignature('4/4'))
     m.makeRests(inPlace=True,
                 fillGaps=True,
                 hideRests=True,
                 timeRangeFromBarDuration=True)
     self.assertLess(m[note.Rest].first().quarterLength, 0.0025)
     gex = GeneralObjectExporter()
     tree = self.getET(gex.fromGeneralObject(m))
     # Only one <forward> tag to get from 1.9979 -> 2.0
     # No <forward> tag is necessary to finish the incomplete measure (3.9979 -> 4.0)
     self.assertEqual(len(tree.findall('.//forward')), 1)
Beispiel #4
0
 def affectTokenAfterParse(self, n):
     '''
     puts a tuplet on the note
     '''
     super(TupletState, self).affectTokenAfterParse(n)
     newTup = duration.Tuplet()
     newTup.durationActual = duration.durationTupleFromTypeDots(n.duration.type, 0)
     newTup.durationNormal = duration.durationTupleFromTypeDots(n.duration.type, 0)
     newTup.numberNotesActual = self.actual
     newTup.numberNotesNormal = self.normal
     n.duration.appendTuplet(newTup)
     return n
Beispiel #5
0
    def setDurationForObject(self, generalNote, durationInfo):
        '''
        generalNote could be a Note, Chord, or Rest
        
        DurationInfo is a string like:
        
            Whole,Dotted,Slur
        
        '''
        from music21 import noteworthy
        dictionaries = noteworthy.dictionaries

        parts = durationInfo.split(',')
        lengthnote = parts[0]
        thisNoteIsSlurred = False
        durationObject = duration.Duration(
            dictionaries["dictionaryNoteLength"][lengthnote])

        for kk in parts:
            if kk == "Grace":
                #print "GRACE NOTE"
                # Now it doesn't work, the function for grace notes have to be added here
                environLocal.warn('skipping grace note')
                return
            elif kk == "Slur":
                #print "SLUR"
                if self.withinSlur is False:
                    self.beginningSlurNote = generalNote
                thisNoteIsSlurred = True
            elif kk == "Dotted":
                durationObject.dots = 1
            elif kk == "DblDotted":
                durationObject.dots = 2

            elif kk == "Triplet" or kk == "Triplet=First" or kk == "Triplet=End":
                tup = duration.Tuplet(3, 2, durationObject.type)
                durationObject.appendTuplet(tup)

        generalNote.duration = durationObject

        # if Slur
        if self.withinSlur is True and thisNoteIsSlurred is False:
            music21SlurObj = spanner.Slur(self.beginningSlurNote, generalNote)
            self.currentMeasure.append(music21SlurObj)
            self.withinSlur = False
        elif thisNoteIsSlurred is True:
            self.withinSlur = True
        else:
            self.withinSlur = False
Beispiel #6
0
    def testStreamLilySemiComplex(self):
        from copy import deepcopy
        from music21 import meter, note, stream, pitch, duration

        a = stream.Stream()
        ts = meter.TimeSignature("3/8")

        b = stream.Stream()
        q = note.EighthNote()

        dur1 = duration.Duration()
        dur1.type = "eighth"

        tup1 = duration.Tuplet()
        tup1.tupletActual = [5, dur1]
        tup1.tupletNormal = [3, dur1]

        q.octave = 2
        q.duration.appendTuplet(tup1)

        for i in range(0, 5):
            b.append(deepcopy(q))
            b.elements[i].accidental = pitch.Accidental(i - 2)

        b.elements[0].duration.tuplets[0].type = "start"
        b.elements[-1].duration.tuplets[0].type = "stop"
        b2temp = b.elements[2]
        c = b2temp.editorial
        c.comment.text = "a real C"

        bestC = b.bestClef(allowTreble8vb=True)
        a.insert(bestC)
        a.insert(ts)
        a.insert(b)

        conv = LilypondConverter()
        outStr = conv.fromObject(a)
        testStr = u'\n  { \\clef "bass"  \\time 3/8  \n  { \\times 3/5 {ceses,8 ces,8 c,8_"a real C" cis,8 cisis,8}   } }'
        #        for i in range(len(outStr)):
        #            self.assertEqual(outStr[i], testStr[i])
        #        print outStr
        #        print testStr

        self.assertEqual(outStr, testStr)
Beispiel #7
0
    def _getNote(self):
        if self._note is not None:
            return self._note
        noteObj = None
        storedtie = None

        stringRep = self.stringRep
        storedDict = self.storedDict

        if stringRep is None:
            raise TinyNotationException(
                'Cannot return a note without some parameters')

        if self.PRECTIE.match(stringRep):
            environLocal.printDebug('Found Front Tie')
            stringRep = self.PRECTIE.sub("", stringRep)
            storedtie = tie.Tie("stop")
            storedDict['lastNoteTied'] = False

        elif 'lastNoteTied' in storedDict and storedDict[
                'lastNoteTied'] is True:
            storedtie = tie.Tie("stop")
            storedDict['lastNoteTied'] = False

        x = self.customPitchMatch(stringRep, storedDict)

        if x is not None:
            noteObj = x
        elif (self.REST.match(stringRep) is not None):  # rest
            noteObj = note.Rest()
        elif (self.OCTAVE2.match(stringRep)):  # BB etc.
            nn = self.OCTAVE2.match(stringRep)
            noteObj = self._getPitch(nn, 3 - len(nn.group(1)))
        elif (self.OCTAVE3.match(stringRep)):
            noteObj = self._getPitch(self.OCTAVE3.match(stringRep), 3)
        elif (self.OCTAVE5.match(stringRep)):  # must match octave 5 then 4!
            nn = self.OCTAVE5.match(stringRep)
            noteObj = self._getPitch(nn, 4 + len(nn.group(2)))
        elif (self.OCTAVE4.match(stringRep)):
            noteObj = self._getPitch(self.OCTAVE4.match(stringRep), 4)
        else:
            raise TinyNotationException(
                "could not get pitch information from " + str(stringRep))

        if storedtie:
            noteObj.tie = storedtie

        ## get duration
        usedLastDuration = False

        if (self.TYPE.search(stringRep)):
            typeNum = self.TYPE.search(stringRep).group(1)
            if (typeNum == "0"):  ## special case = full measure + fermata
                if 'barDuration' in storedDict:
                    noteObj.duration = storedDict['barDuration']
                newFerm = expressions.Fermata()
                noteObj.expressions.append(newFerm)
            else:
                noteObj.duration.type = duration.typeFromNumDict[int(typeNum)]
        else:
            if 'lastDuration' in storedDict:
                noteObj.duration = copy.deepcopy(storedDict['lastDuration'])
                usedLastDuration = True
            if (noteObj.duration.tuplets):
                noteObj.duration.tuplets[0].type = ""
                # if it continues a tuplet it cannot be start; maybe end

        ## get dots; called out because subclassable
        self.getDots(stringRep, noteObj)

        ## get ties
        if self.TIE.search(stringRep):
            environLocal.printDebug('Found Tie Tie')
            storedDict['lastNoteTied'] = True
            if noteObj.tie is None:
                noteObj.tie = tie.Tie("start")
            else:
                noteObj.tie.type = 'continue'

        ## use dict to set tuplets
        if ((('inTrip' in storedDict and storedDict['inTrip'] == True) or
             ('inQuad' in storedDict and storedDict['inQuad'] == True))
                and usedLastDuration == False):
            newTup = duration.Tuplet()
            newTup.durationActual.type = noteObj.duration.type
            newTup.durationNormal.type = noteObj.duration.type
            if 'inQuad' in storedDict and storedDict['inQuad'] == True:
                newTup.numNotesActual = 4.0
                newTup.numNotesNormal = 3.0
            if 'beginTuplet' in storedDict and storedDict[
                    'beginTuplet'] == True:
                newTup.type = "start"
            noteObj.duration.appendTuplet(newTup)

        if ((('inTrip' in storedDict and storedDict['inTrip'] == True) or
             ('inQuad' in storedDict and storedDict['inQuad'] == True)) and
            ('endTuplet' in storedDict and storedDict['endTuplet'] == True)):
            noteObj.duration.tuplets[0].type = "stop"

        storedDict['lastDuration'] = noteObj.duration

        ## get accidentals
        if (isinstance(noteObj, note.Note)):
            if (self.EDSHARP.search(stringRep)):  # must come before sharp
                alter = len(self.EDSHARP.search(stringRep).group(1))
                acc1 = pitch.Accidental(alter)
                noteObj.editorial.ficta = acc1
                noteObj.editorial.misc['pmfc-ficta'] = acc1
            elif (self.EDFLAT.search(stringRep)):  # must come before flat
                alter = -1 * len(self.EDFLAT.search(stringRep).group(1))
                acc1 = pitch.Accidental(alter)
                noteObj.editorial.ficta = acc1
                noteObj.editorial.misc['pmfc-ficta'] = acc1
            elif (self.EDNAT.search(stringRep)):
                acc1 = pitch.Accidental("natural")
                noteObj.editorial.ficta = acc1
                noteObj.editorial.misc['pmfc-ficta'] = acc1
                noteObj.accidental = acc1
            elif (self.SHARP.search(stringRep)):
                alter = len(self.SHARP.search(stringRep).group(1))
                noteObj.accidental = pitch.Accidental(alter)
            elif (self.FLAT.search(stringRep)):
                alter = -1 * len(self.FLAT.search(stringRep).group(1))
                noteObj.accidental = pitch.Accidental(alter)

        self.customNotationMatch(noteObj, stringRep, storedDict)

        if self.ID_EL.search(stringRep):
            noteObj.id = self.ID_EL.search(stringRep).group(1)

        if self.LYRIC.search(stringRep):
            noteObj.lyric = self.LYRIC.search(stringRep).group(1)

        self._note = noteObj
        return self._note
Beispiel #8
0
def get_note_duration(pitch, note_length, denom):
    dur = None
    #3/2
    if denom == 3:
        if math.isclose(note_length, (1 / 3)):
            dur = duration.Duration(type='eighth')
        elif math.isclose(note_length, (2 / 3)):
            dur = duration.Duration(type='quarter')
        dur.appendTuplet(duration.Tuplet(3, 2, 'eighth'))

    #5/4
    elif denom == 5:
        if math.isclose(note_length, (1 / 5)):
            dur = duration.Duration(type='16th')
        elif math.isclose(note_length, (2 / 5)):
            print("here")
            dur = duration.Duration(type='eighth')
        elif math.isclose(note_length, (3 / 5)):
            dur = duration.Duration(type='eighth', dots=1)
        elif math.isclose(note_length, (4 / 5)):
            dur = duration.Duration(type='quarter')
        dur.appendTuplet(duration.Tuplet(5, 4, '16th'))

    #6/4
    elif denom == 6:
        if math.isclose(note_length, (1 / 6)):
            dur = duration.Duration(type='16th')
        elif math.isclose(note_length, (2 / 6)):
            dur = duration.Duration(type='eighth')
        elif math.isclose(note_length, (3 / 6)):
            dur = duration.Duration(type='eighth', dots=1)
        elif math.isclose(note_length, (4 / 6)):
            dur = duration.Duration(type='quarter')
        elif math.isclose(note_length, (5 / 6)):
            note1 = m21note.Note(pitch)
            note1.duration = duration.Duration(type='eighth', dots=1)
            note1.duration.appendTuplet(duration.Tuplet(6, 4, '16th'))
            note1.tie = tie.Tie('start')
            note2 = m21note.Note(pitch)
            note2.duration = duration.Duration(type='eighth')
            note2.duration.appendTuplet(duration.Tuplet(6, 4, '16th'))
            return [note1, note2]
        dur.appendTuplet(duration.Tuplet(6, 4, '16th'))

    #7/4
    elif denom == 7:
        if math.isclose(note_length, (1 / 7)):
            dur = duration.Duration(type='16th')
        elif math.isclose(note_length, (2 / 7)):
            dur = duration.Duration(type='eighth')
        elif math.isclose(note_length, (3 / 7)):
            dur = duration.Duration(type='eighth', dots=1)
        elif math.isclose(note_length, (4 / 7)):
            dur = duration.Duration(type='quarter')
        elif math.isclose(note_length, (5 / 7)):
            note1 = m21note.Note(pitch)
            note1.duration = duration.Duration(type='eighth', dots=1)
            note1.duration.appendTuplet(duration.Tuplet(7, 4, '16th'))
            note1.tie = tie.Tie('start')
            note2 = m21note.Note(pitch)
            note2.duration = duration.Duration(type='eighth')
            note2.duration.appendTuplet(duration.Tuplet(7, 4, '16th'))
            return [note1, note2]
        elif math.isclose(note_length, (6 / 7)):
            dur = duration.Duration(type='quarter', dots=1)
        dur.appendTuplet(duration.Tuplet(7, 4, '16th'))

    #9/8
    elif denom == 9:
        if math.isclose(note_length, (1 / 9)):
            dur = duration.Duration(type='32nd')
        elif math.isclose(note_length, (2 / 9)):
            dur = duration.Duration(type='16th')
        elif math.isclose(note_length, (3 / 9)):
            dur = duration.Duration(type='16th', dots=1)
        elif math.isclose(note_length, (4 / 9)):
            dur = duration.Duration(type='eighth')
        elif math.isclose(note_length, (5 / 9)):
            note1 = m21note.Note(pitch)
            note1.duration = duration.Duration(type='16th', dots=1)
            note1.duration.appendTuplet(duration.Tuplet(9, 8, '32nd'))
            note1.tie = tie.Tie('start')
            note2 = m21note.Note(pitch)
            note2.duration = duration.Duration(type='16th')
            note2.duration.appendTuplet(duration.Tuplet(9, 8, '32nd'))
            return [note1, note2]
        elif math.isclose(note_length, (6 / 9)):
            dur = duration.Duration(type='eighth', dots=1)
        elif math.isclose(note_length, (7 / 9)):
            dur = duration.Duration(type='eighth', dots=2)
        elif math.isclose(note_length, (8 / 9)):
            dur = duration.Duration(type='quarter')
        dur.appendTuplet(duration.Tuplet(9, 8, '32nd'))

    note = m21note.Note(pitch)
    if dur is None:
        print(f"NOTE_LENGTH:{note_length} DENOM:{denom}")
        print("------")
        print()
    note.duration = dur
    return [note]