How to use the music21.stream 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 ringw / homer / metaomr / note.py View on Github external
def get_notepitch_score(page):
    # Parts must be consistent for each system
    assert (np.diff([s['stop'] - s['start'] for s in page.systems]) == 0).all()

    get_notepitches(page)

    doc = music21.stream.Stream()
    for part_num in xrange(page.systems[0]['stop']+1 - page.systems[0]['start']):
        part = music21.stream.Part()
        for bar in page.bars:
            staff = [measure[part_num] for measure in bar]
            for m in staff:
                pitchMeasure = music21.stream.Measure()
                if hasattr(m, 'notepitches'):
                    for notePitch in m.notepitches:
                        note = music21.note.Note(notePitch.pitch)
                        pitchMeasure.append(note)
                part.append(pitchMeasure)
        doc.insert(0, part)
    return doc
github cuthbertLab / music21 / music21 / graph.py View on Github external
# see if this stream has any Measures, or has any references to
        # Measure obtained through contexts
        # look at measures first, as this will always be faster
        environLocal.printDebug(['ticksOffset: about to call measure offset', self.streamObj])

        if self.streamObj.hasPartLikeStreams():
            # if we have part-like sub streams; we can assume that all parts
            # have parallel measures start times here for simplicity
            # take the top part 
            environLocal.printDebug(['found partLikeStreams', self.streamObj.parts[0]])

            offsetMap = self.streamObj.parts[0].measureOffsetMap(
                        ['Measure'])
        elif self.streamObj.hasMeasures():
            offsetMap = self.streamObj.measureOffsetMap([stream.Measure])
        else:
            offsetMap = self.streamObj.measureOffsetMap([note.Note])

        if len(offsetMap.keys()) > 0:
            self._axisLabelUsesMeasures = True
        else:
            self._axisLabelUsesMeasures = False

        environLocal.printDebug(['ticksOffset: got offset map keys', offsetMap.keys(), self._axisLabelUsesMeasures])


        ticks = [] # a list of graphed value, string label pairs
        if len(offsetMap.keys()) > 0:
            #environLocal.printDebug(['using measures for offset ticks'])
            # store indices in offsetMap
            mNoToUse = []
github cuthbertLab / music21 / music21 / repeat.py View on Github external
def testFilterByRepeatMark(self):
        from music21 import stream, bar, repeat, note

        s = stream.Part()
        m1 = stream.Measure()
        m1.leftBarline = bar.Repeat(direction='start')
        m1.rightBarline = bar.Repeat(direction='end', times=2)
        m1.repeatAppend(note.Note('g3', quarterLength=1), 4)

        self.assertEqual(len(m1.getElementsByClass('RepeatMark')), 2)

        m2 = stream.Measure()
        m2.leftBarline = bar.Repeat(direction='start')
        m2.rightBarline = bar.Repeat(direction='end', times=2)
        m2.repeatAppend(note.Note('d4', quarterLength=1), 4)

        s.append(m1)
        s.append(m2)

        #s.show()
github cuthbertLab / music21 / music21 / stream / iterator.py View on Github external
def testSimpleClone(self):
        from music21 import note, stream
        s = stream.Stream()
        r = note.Rest()
        n = note.Note()
        s.append([r, n])
        all_s = list(s.iter)
        self.assertEqual(len(all_s), 2)
        self.assertIs(all_s[0], r)
        self.assertIs(all_s[1], n)
        s_notes = list(s.iter.notes)
        self.assertEqual(len(s_notes), 1)
        self.assertIs(s_notes[0], n)
github shimpe / canon-generator / canon-gen.py View on Github external
def spiceup_streams(streams, scale, repetitions=1):  
  """
  function that takes a stream of parts
  and spices up every part using the
  Identity, OneToThree, TwoToThree, TwoToFour, ... 
  transformations

  * it requires a scale in which to interpret the streams
  * it can create "repetitions" spiced sequences of the given stream
  """
  newtotalstream = music21.stream.Stream()
  for i, part in enumerate(streams):
    newstream = music21.stream.Stream()
    for x in range(repetitions):
      for note, nextnote in pairwise(part.notesAndRests):
        new_note = copy.deepcopy(note)
        new_nextnote = copy.deepcopy(nextnote)
        method = random.choice(methods)
        if method == SINGLE_NOTE:
          trafo = random.choice(single_note_transformers)()
          newstream.append(trafo.transform(scale, new_note).flat.elements)
        elif method == DOUBLE_NOTE:
          trafo = random.choice(double_note_transformers)()
          newstream.append(trafo.transform(scale, new_note, new_nextnote).flat.elements)
    newtotalstream.insert(0, newstream)
  return newtotalstream
github cuthbertLab / music21-tools / misc / gatherAccidentals.py View on Github external
def testGetAccidentalCountBasic(self):
        s = stream.Stream()
        self.assertEqual(len(s.flat.notes), 0) # the stream should be empty
        self.assertEqual(getAccidentalCount(s), {})
github cuthbertLab / music21 / music21 / alpha / medren.py View on Github external
'''
    Converts any right barlines in the previous style (oldStyle; default='regular')
    to have the newStyle (such as 'tick', 'none', etc., see bar.py).

    Leaves alone any other barline types (such as
    double bars, final bars, etc.).  Also changes any measures with no specified
    barlines (which come out as 'regular') to have the new style.

    returns the Score object.
    '''
    if inPlace is False:
        score = copy.deepcopy(score)

    oldStyle = oldStyle.lower()
    for m in score.semiFlat:
        if isinstance(m, stream.Measure):
            barline = m.rightBarline
            if barline is None:
                m.rightBarline = bar.Barline(style=newStyle)
            else:
                if barline.style == oldStyle:
                    barline.style = newStyle
    return score
github cuthbertLab / music21 / music21 / figuredBass / realizer.py View on Github external
def generateRealizationFromPossibilityProgression(self, possibilityProgression):
        '''
        Generates a realization as a :class:`~music21.stream.Score` given a possibility progression.
        '''
        sol = stream.Score()

        bassLine = stream.Part()
        bassLine.append([copy.deepcopy(self._keySig), copy.deepcopy(self._inTime)])
        r = None
        if self._paddingLeft != 0.0:
            r = note.Rest(quarterLength=self._paddingLeft)
            bassLine.append(copy.deepcopy(r))

        if self.keyboardStyleOutput:
            rightHand = stream.Part()
            sol.insert(0.0, rightHand)
            rightHand.append([copy.deepcopy(self._keySig), copy.deepcopy(self._inTime)])
            if r is not None:
                rightHand.append(copy.deepcopy(r))

            for segmentIndex in range(len(self._segmentList)):
                possibA = possibilityProgression[segmentIndex]
                bassNote = self._segmentList[segmentIndex].bassNote
github ahankinson / music21-mei / converter_old.py View on Github external
def _getMeasures(self):
        # staffdefs = self._meiDoc.search('staffdef')
        # for staffdef in staffdefs:
        #     s = stream.Part()
        
        measures = self._meiDoc.search('measure')
        for measure in measures:
            lg.debug("Measure ID: {0}".format(measure.id))
            m = stream.Measure()
            
            m.timeSignature = self._timesig
            m.keySignature = self._keysig
            
            staves = measure.descendents_by_name('staff')
            
            # set up a measure number.
            m.number = int(measure.attribute_by_name('n').value)
            
            # deal with barlines
            # We have to use MusicXML's barline notation here.
            barline = measure.attribute_by_name('right')
            if barline:
                b_value = barline.getvalue()
                if b_value == "rptstart":
                    b = bar.Repeat()
github cuthbertLab / music21 / music21 / meter.py View on Github external
def testBasic(self):
        from music21 import stream
        a = stream.Stream()
        for meterStrDenominator in [1,2,4,8,16,32]:
            for meterStrNumerator in [2,3,4,5,6,7,9,11,12,13]:
                ts = music21.meter.TimeSignature('%s/%s' % (meterStrNumerator, 
                                                            meterStrDenominator))
                m = stream.Measure()
                m.timeSignature = ts
                a.insert(m.timeSignature.barDuration.quarterLength, m)
        a.show()