How to use music21 - 10 common examples

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 / musedata / base40.py View on Github external
try:
        simpleIntervalName = base40IntervalTable[simpleDelta]
        simpleInterval = interval.Interval(simpleIntervalName)
    except KeyError:
        raise Base40Exception('Interval not handled by Base40 ' + str(simpleDelta))

    numOctaves = abs(delta) // 40

    sgi = simpleInterval.generic  # Simple generic interval
    # Compound generic interval
    cgi = interval.GenericInterval(direction * (sgi.value + 7 * numOctaves))
    sdi = simpleInterval.diatonic  # Simple diatonic interval

    newInterval = str(sdi.specifier) + str(cgi.value)

    return interval.Interval(newInterval)
github cuthbertLab / music21 / music21 / metadata / testMetadata.py View on Github external
def testRichMetadata02(self):
        from music21 import corpus
        from music21 import metadata

        score = corpus.parse('bwv66.6')
        richMetadata = metadata.RichMetadata()
        richMetadata.merge(score.metadata)
        richMetadata.update(score)
        self.assertEqual(richMetadata.noteCount, 165)
        self.assertEqual(richMetadata.quarterLength, 36.0)
github cuthbertLab / music21 / music21 / mei / test_base.py View on Github external
def testTuplets10(self):
        '''
        _postGuessTuplets(): integration test that a single-part Score with one triplet is guessed
        '''
        # setup the Voice with tuplets
        theVoice = stream.Voice()
        for _ in range(3):
            eachNote = note.Note('D-5', quarterLength=0.5)
            theVoice.append(eachNote)
        theVoice[0].m21TupletSearch = 'start'
        theVoice[0].m21TupletNum = '3'
        theVoice[0].m21TupletNumbase = '2'
        theVoice[2].m21TupletSearch = 'stop'
        theVoice[2].m21TupletNum = '3'
        theVoice[2].m21TupletNumbase = '2'
        # setup the Score->Part->Measure->Voice hierarchy
        theMeasure = stream.Measure([theVoice])
        thePart = stream.Part([theMeasure])
        theScore = stream.Score(givenElements=[thePart])
        # make the expected values
        expectedOffsets = [0.0, Fraction(1, 3), Fraction(2, 3)]

        actual = base._postGuessTuplets(theScore)
github shimpe / canon-generator / canon-gen.py View on Github external
############################################################################

  # prepare some streams: one per voice
  # all bass notes of each chord form one voice
  # all 2nd notes of each chord form a second voice
  # ...
  # convert chords to notes and stuff into a stream
  streams = {}
  splitted_chords = chords.split(" ")
  for v in range(voices):
    streams[v] = music21.stream.Stream()
  # split each chord into a separate voice
  for c in splitted_chords:
    pitches = realize_chord(c, voices, octave, direction="descending")
    for v in range(voices):
      note = music21.note.Note(pitches[v])
      note.quarterLength = quarterLength
      streams[v].append(note)

  # combine all voices to one big stream
  totalstream = music21.stream.Stream()
  for r in range(stacking):
    for s in streams:
      totalstream.insert(0, copy.deepcopy(streams[s]))

  # add some spice to the boring chords. sugar and spice is always nice
  spiced_streams = [totalstream]
  for s in range(spice_depth):
    # each iteration spices up the stream that was already spiced up in the previous iteration,
    # leading to spicier and spicier streams
    spiced_streams.append(spiceup_streams(spiced_streams[s], scale))
github cuthbertLab / music21 / music21 / alpha / webapps / server / zipfileapp.py View on Github external
Function that determines what command to perform on the score and returns the resulting score.
    Currently is a lookup table based on the URL,
    but will be improved and incorporated into webapps/__init__.py
    as it changes to allow for more standard music21 functions
    '''
    commandParts = command.split("/")
    if (len(commandParts) < 3):
        raise exceptions21.Music21Exception("Not enough parts on the command")

    if commandParts[1] == "transpose":
        return sc.transpose(commandParts[2])

    elif commandParts[1] == "allCMajor":
        key = sc.analyze('key')
        (p, unused_mode) = key.pitchAndMode
        intv = interval.Interval(note.Note(p),note.Note('C'))

        for ks in sc.flat.getElementsByClass('KeySignature'):
            ks.transpose(intv, inPlace = True)
        sc.transpose(intv, inPlace = True)
        return sc

    elif commandParts[1] == "addReduction":
        reductionStream = reduction(sc)
        sc.insert(0,reductionStream)
        return sc

    elif commandParts[1] == "reduction":
        reductionStream = reduction(sc)
        return reductionStream

    elif commandParts[1] == "scaleDegrees":
github cuthbertLab / music21 / music21 / demos / composition / aug30.py View on Github external
def test():
    from music21 import instrument as j
    sc1 = stream.Score()
#    instruments = [Piccolo(), Glockenspiel(), 72, 69, 41, 27, 47, 1, 1, 1, 1, 34]
    instrument = [j.Piccolo(), j.Xylophone(), j.Clarinet(), j.Oboe(), j.Violin(),
                  j.ElectricGuitar(), j.Harp(), j.Piano(), j.Piano(), j.Piano(), j.Piano(), j.ElectricBass()]
    instrumentOctave = [3, 2, 2, 2, 1, 1, 1, 2, 1, 0, -1, -2]

    for i in range(12):
        inst = instrument[i]
        if i < 9:
            inst.midiChannel = i
        else:
            inst.midiChannel = i + 1
        part = addPart(instrument=inst)
        if instrumentOctave[i] != 0:
            part.transpose(12 * instrumentOctave[i], inPlace=True)
        sc1.insert(0, part)
    sc1.show()
github cuthbertLab / music21 / music21 / noteworthy / translate.py View on Github external
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
github cuthbertLab / music21 / music21 / text.py View on Github external
match = leading
            break
    if match is not None:
        # recombine everything except the last comma split
        return ' '.join(src.split(' ')[1:]) + ', %s' % match
    else:  # not match
        return src


# ------------------------------------------------------------------------------
class TextException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class TextBoxException(exceptions21.Music21Exception):
    pass


# ------------------------------------------------------------------------------
class TextBox(base.Music21Object):
    '''
    A TextBox is arbitrary text that might be positioned anywhere on a page,
    independent of notes or staffs. A page attribute specifies what page this text is found on;
    style.absoluteY and style.absoluteX position the text from the bottom left corner in
    units of tenths.

    This object is similar to the TextExpression object, but does not have as many position
    parameters, enclosure attributes, and the ability to convert to
    RepeatExpressions and TempoTexts.

    >>> from music21 import text, stream
github cuthbertLab / music21 / music21 / alpha / webapps / server / zipfileapp.py View on Github external
def performFunction(sc, command):
    '''
    Function that determines what command to perform on the score and returns the resulting score.
    Currently is a lookup table based on the URL,
    but will be improved and incorporated into webapps/__init__.py
    as it changes to allow for more standard music21 functions
    '''
    commandParts = command.split("/")
    if (len(commandParts) < 3):
        raise exceptions21.Music21Exception("Not enough parts on the command")

    if commandParts[1] == "transpose":
        return sc.transpose(commandParts[2])

    elif commandParts[1] == "allCMajor":
        key = sc.analyze('key')
        (p, unused_mode) = key.pitchAndMode
        intv = interval.Interval(note.Note(p),note.Note('C'))

        for ks in sc.flat.getElementsByClass('KeySignature'):
            ks.transpose(intv, inPlace = True)
        sc.transpose(intv, inPlace = True)
        return sc

    elif commandParts[1] == "addReduction":
        reductionStream = reduction(sc)
github cuthbertLab / music21 / music21 / alpha / analysis / fixer.py View on Github external
'omr': measure stream,
                'expected': measure stream,
            }
            '''
            omrMeasure = stream.Measure()
            omrNote = note.Note('F')
            omrNote.duration = duration.Duration('whole')
            omrMeasure.append(omrNote)

            expectedFixedOmrMeasure = stream.Stream()
            expectedOmrNote = deepcopy(omrNote)
            expectedOmrNote.expressions.append(expressions.Turn())
            expectedFixedOmrMeasure.append(expectedOmrNote)

            midiMeasure = stream.Measure()
            turn = [note.Note('G'), note.Note('F'), note.Note('E'), note.Note('F')]
            midiMeasure.append(turn)

            returnDict = {
                'name': 'Single Turn Measure',
                'midi': midiMeasure,
                'omr': omrMeasure,
                'expected': expectedFixedOmrMeasure,
            }
            return returnDict