How to use the music21.note.Rest function in music21

To help you get started, we’ve selected a few music21 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cuthbertLab / music21 / music21 / humdrum / spineParser.py View on Github external
matchedNote = re.search("([a-gA-G]+)", contents)

    thisObject = None
    if matchedNote:
        kernNoteName = matchedNote.group(1)
        step = kernNoteName[0].lower()
        if (step == kernNoteName[0]): ## middle C or higher
            octave = 3 + len(kernNoteName)
        else: # below middle C
            octave = 4 - len(kernNoteName)
        thisObject = note.Note(octave = octave)
        thisObject.step = step

    # 3.3 -- Rests
    elif contents.count("r"):
        thisObject = note.Rest()
    else:
        raise HumdrumException("Could not parse %s for note information" % contents)

    matchedSharp = re.search(r"(\#+)", contents)
    matchedFlat  = re.search(r"(\-+)", contents)

    if matchedSharp:
        thisObject.accidental = matchedSharp.group(0)
    elif matchedFlat:
        thisObject.accidental = matchedFlat.group(0)
    elif contents.count("n"):
        thisObject.accidental = "n"

    # 3.2.2 -- Slurs, Ties, Phrases
    # TODO: add music21 phrase information
    if contents.count('{'):
github cuthbertLab / music21 / music21 / analysis / reduction.py View on Github external
def testPartReductionE(self):
        '''Artificially create test cases.
        '''
        from music21 import dynamics, analysis
        s = stream.Score()
        p1 = stream.Part()
        p1.id = 0
        p2 = stream.Part()
        p2.id = 1
        for ql in [2, 2, False, 2, False, 2]:
            if ql:
                p1.append(note.Note(quarterLength=ql))
                p2.append(note.Note(quarterLength=ql))
            else:
                p1.append(note.Rest(quarterLength=2))
                p2.append(note.Rest(quarterLength=2))
        for pos, dyn in [(0, 'p'), (2, 'fff'), (6, 'ppp')]:
            p1.insert(pos, dynamics.Dynamic(dyn))
        for pos, dyn in [(0, 'mf'), (2, 'f'), (6, 'mf')]:
            p2.insert(pos, dynamics.Dynamic(dyn))
        p1.makeMeasures(inPlace=True)
        p2.makeMeasures(inPlace=True)
        s.insert(0, p1)
        s.insert(0, p2)
        # s.show()
        pr = analysis.reduction.PartReduction(s, fillByMeasure=True,
                    segmentByTarget=False, normalize=False)
        pr.process()
        target = pr.getGraphHorizontalBarWeightedData()
        match = [(0, [[0.0, 4.0, 0.178571428571, '#666666'],
                      [4.0, 4.0, 0.0214285714286, '#666666'],
github cuthbertLab / music21 / music21 / alpha / analysis / ornamentRecognizer.py View on Github external
testConditions = []

        n1Duration = duration.Duration('quarter')
        t1NumNotes = 4
        t1UpInterval = interval.Interval('M2')
        t1DownInterval = interval.Interval('M-2')
        n1Lower = note.Note('G')
        n1Lower.duration = n1Duration
        n1Upper = note.Note('A')
        n1Upper.duration = n1Duration
        t1 = expressions.Trill()
        t1NoteDuration = calculateTrillNoteDuration(t1NumNotes, n1Duration)
        t1.quarterLength = t1NoteDuration
        t1Notes = t1.realize(n1Lower)[0]  # GAGA
        t1NotesWithRest = deepcopy(t1Notes)  # GA_A
        r1 = note.Rest()
        r1.duration = duration.Duration(t1NoteDuration)
        t1NotesWithRest[2] = r1
        testConditions.append(
            _TestCondition(
                name='even whole step trill up without simple note',
                busyNotes=t1Notes,
                isOrnament=True,
                ornamentSize=t1UpInterval)
        )
        testConditions.append(
            _TestCondition(
                name='even whole step trill up from simple note',
                busyNotes=t1Notes,
                simpleNotes=[n1Lower],
                isOrnament=True,
                ornamentSize=t1UpInterval)
github cuthbertLab / music21 / music21 / musicxml / fromMxObjects.py View on Github external
def testTextExpressionsE(self):
        import random
        s = stream.Stream()
        for i in range(6):
            m = stream.Measure(number=i + 1)
            m.append(layout.SystemLayout(isNew=True))
            m.append(note.Rest(type='whole'))
            s.append(m)
        for m in s.getElementsByClass('Measure'):
            offsets = [x * .25 for x in range(16)]
            random.shuffle(offsets)
            offsets = offsets[:4]
            for o in offsets:
                te = expressions.TextExpression(o)
                te.style = 'bold'
                te.justify = 'center'
                te.enclosure = 'rectangle'
                m.insert(o, te)
        #s.show()      
github cuthbertLab / music21 / music21 / demos / icmc2011.py View on Github external
#s1.flat.show('t')

        # lengths show the number of elements; indices are sequential
        s1Flat = s1.flat
        assert len(s1) == 2
        assert len(s1Flat) == 6
        assert s1Flat[4] == n3
        assert s1Flat[5] == n4

        # adding another Part to the Score results in a different flat representation
        n5 = note.Note('a#1', quarterLength=2.5)
        n6 = note.Note('b2', quarterLength=1.5)
        m4 = stream.Measure(number=2)
        m4.append([n5, n6])

        r1 = note.Rest(type='whole')
        cf2 = clef.bestClef(m4) # = BassClef
        m3 = stream.Measure(number=1)
        m3.append([cf2, r1])

        p2 = stream.Part()
        p2.append([m3, m4])
        s1.insert(0, p2)

        assert 'BassClef' in cf2.classes

        # objects are sorted by offset
        s1Flat = s1.flat
        assert len(s1) == 3
        assert len(s1.flat) == 10
        assert s1Flat[6] == n3
        assert s1Flat[7] == n5
github cuthbertLab / music21 / music21 / musicxml / fromMxObjects.py View on Github external
def mxToRest(mxNote, inputM21=None):
    '''Translate a MusicXML :class:`~music21.musicxml.Note` object to a :class:`~music21.note.Rest`.

    If an `inputM21` object reference is provided, this object will be configured; otherwise, a new :class:`~music21.note.Rest` object is created and returned.
    '''
    if inputM21 == None:
        r = note.Rest()
    else:
        r = inputM21

    try:
        mxToDuration(mxNote, r.duration)
    except duration.DurationException:
        #environLocal.printDebug(['failed extaction of duration from musicxml', 'mxNote:', mxNote, r])
        raise

    if mxNote.get('color') is not None:
        r.color = mxNote.get('color')

    return r
github cuthbertLab / music21 / music21 / note.py View on Github external
A Music21 rest is equal to another object if that object is also a rest which
        has the same duration.


        >>> r1 = note.Rest()
        >>> r2 = note.Rest()
        >>> r1 == r2
        True
        >>> r2.duration.quarterLength = 4.0/3
        >>> r1 == r2
        False
        >>> r1 == note.Note()
        False
        '''

        return isinstance(other, Rest) and self.duration == other.duration
github cuthbertLab / music21 / music21 / mei / base.py View on Github external
elif eachElem.tag not in _IGNORE_UNPROCESSED:
            environLocal.printDebug(_UNPROCESSED_SUBELEMENT.format(eachElem.tag, elem.tag))

    # Process objects from a ...
    # We must process them now because, if we did it in the loop above, the respective  may
    # not be processed before the .
    for whichN, eachDict in six.iteritems(stavesWaiting):
        for eachObj in six.itervalues(eachDict):
            # We must insert() these objects because a  signals its changes for the
            # *start* of the  in which it appears.
            staves[whichN].insert(0, eachObj)

    # create rest-filled measures for expected parts that had no  tag in this 
    for eachN in expectedNs:
        if eachN not in staves:
            restVoice = stream.Voice([note.Rest(quarterLength=maxBarDuration)])
            restVoice.id = '1'
            restVoice[0].m21wasMRest = True  # just in case (e.g., when all the other voices are )
            staves[eachN] = stream.Measure([restVoice], number=int(elem.get('n', backupNum)))

    # First search for Rest objects created by an  element that didn't have @dur set. This
    # will only work in cases where not all of the parts are resting. However, it avoids a more
    # time-consuming search later.
    if (maxBarDuration == _DUR_ATTR_DICT[None] and
        activeMeter is not None and
        maxBarDuration != activeMeter.totalLength):
        # In this case, all the staves have  elements without a @dur.
        _correctMRestDurs(staves, activeMeter.totalLength)
    else:
        # In this case, some or none of the staves have an  element without a @dur.
        _correctMRestDurs(staves, maxBarDuration)
github cuthbertLab / music21 / music21 / musedata / translate.py View on Github external
eLast = _processPending(hasVoices, pendingRecords, eLast, m, vActive)
                    pendingRecords = []

                # every time we encounter a back, we need to store
                # our existing voice and create a new one
                m.insert(0, vActive)
                vActive = stream.Voice()

            if mdr.isRest():
                # environLocal.printDebug(['got mdr rest, parent:', mdr.parent])
                # check for pending records first
                if pendingRecords != []:
                    eLast = _processPending(hasVoices, pendingRecords, eLast, m, vActive)
                    pendingRecords = []
                # create rest after clearing pending records
                r = note.Rest()
                r.quarterLength = mdr.getQuarterLength()
                if hasVoices:
                    vActive.coreAppend(r)
                else:
                    m.coreAppend(r)
                eLast = r
                continue
            # a note is note as chord, but may have chord tones
            # attached to it that follow
            elif mdr.isChord():
                # simply append if a chord; do not clear or change pending
                pendingRecords.append(mdr)

            elif mdr.isNote():
                # either this is a note alone, or this is the first
                # note found that is not a chord; if first not a chord
github cuthbertLab / music21 / music21 / mei / base.py View on Github external
- (att.layerident (@layer)))

        - (att.fermatapresent (@fermata))

            - (att.tupletpresent (@tuplet))
            - (att.rest.log.cmn (att.beamed (@beam)))

    - att.rest.vis (all)
    - att.rest.ges (all)
    - att.rest.anl (all)

    **Contained Elements not Implemented:** none
    '''
    # NOTE: keep this in sync with spaceFromElement()

    theRest = note.Rest(duration=makeDuration(_qlDurationFromAttr(elem.get('dur')),
                                              int(elem.get('dots', 0))))

    if elem.get(_XMLID) is not None:
        theRest.id = elem.get(_XMLID)

    # tuplets
    if elem.get('m21TupletNum') is not None:
        theRest = scaleToTuplet(theRest, elem)

    return theRest