def __init__(self, scaleValue='C', scaleMode='major'):
        '''
        Acts as a wrapper for :class:`~music21.scale.Scale`. Used to represent the
        concept of a figured bass scale, with a scale value and mode.
        
        
        Accepted scale types: major, minor, dorian, phrygian, and hypophrygian.
        A FiguredBassScale is raised if an invalid scale type is provided.
        
        >>> from music21.figuredBass import realizerScale
        >>> fbScale = realizerScale.FiguredBassScale()
        >>> fbScale.realizerScale
        <music21.scale.MajorScale C major>
        >>> fbScale.keySig
        <music21.key.KeySignature of no sharps or flats>

        >>> fbScale = realizerScale.FiguredBassScale('d', 'minor')
        >>> fbScale.realizerScale
        <music21.scale.MinorScale D minor>
        >>> fbScale.keySig
        <music21.key.KeySignature of 1 flat>
        '''
        try:
            foo = scaleModes[scaleMode]
            self.realizerScale = foo(scaleValue)
            self.keySig = key.KeySignature(
                key.pitchToSharps(scaleValue, scaleMode))
        except KeyError:
            raise FiguredBassScaleException("Unsupported scale type-> " +
                                            scaleMode)
Example #2
0
def cycle36_a_minor_test():
    sc = scale.MinorScale('A')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'A4',
                                                         'G5'))
    cycle = generate_cycle_pair(sc, tonic_triad, "3/6")
    cycle.insert(0, key.KeySignature(0))
    cycle.show()
Example #3
0
def ch5_writing_IV_A(show=True, *arguments, **keywords):
    '''p. 50

    Note the meter signature, then add bar lines. 
    '''
    from music21 import stream, meter, key
    ex = stream.Stream()
    
    ex.insert(clef.BassClef())
    ex.insert(meter.TimeSignature('6/4'))
    ex.insert(key.KeySignature(3))
    
    for p, d in [(None,1), ('f#3',1),('g#3',1),('a3',4),
                 ('g#3',.5),('a#3',.5),('b3',2),
                 ('a#3',.5),('g#3',.5),('a#3',.5),('b#3',.5),
                 ('c#4',1.5),('b3',.5),('a3',.5),('c#4',.5),('b3',.5),('a3',.5),
                 ('g#3',2),('f#3',3), (None,.5), ('c#4',.5),('c#4',.5),
                 ('b3',.5),('b3',.5),('a#3',.5)]:
        if p == None: 
            n = note.Rest()
        else:
            n = note.Note(p)
        n.quarterLength = d
        ex.append(n)
    
    if show:
        # calling show creates measures and allocates notes for the time sig
        ex.show()
    else:
        unused_post = musicxml.m21ToString.fromMusic21Object(ex)
Example #4
0
 def createKey(self, attributes):
     r'''
     Adds a new key signature to the given measure.  
     Returns the number of sharps (negative for flats)
     
     
     
     >>> measureIn = stream.Measure()
     >>> measureIn.append(note.Rest(quarterLength = 3.0))
     
     >>> nwt = noteworthy.translate.NoteworthyTranslator()
     >>> nwt.currentMeasure = measureIn
     >>> nwt.createKey({'Signature':'F#,C#,G#,D#'})
     >>> nwt.currentKey.sharps
     4
     >>> measureIn.show('text')
     {0.0} <music21.note.Rest rest>
     {3.0} <music21.key.KeySignature of 4 sharps>
     '''  
     ke = attributes['Signature']
     currentSharps = 0
     for a in range(len(ke)):
         if ke[a] == "#":
             currentSharps = currentSharps + 1          
         if ke[a] == "b":
             currentSharps = currentSharps - 1
     currentKey = key.KeySignature(currentSharps)
     self.currentMeasure.append(currentKey)
     self.currentKey = currentKey
Example #5
0
def happyBirthday():
    hb = cp("tinynotation: 3/4 d8. d16 e4 d g f#2 d8. d16 e4 d a g2 d8. d16 d'4 b g8. g16 f#4 e c'8. c'16 b4 g a g2")
    hb.insert(0, key.KeySignature(1))
    hb.insert(0, tempo.TempoText("Brightly"))
    hb.insert(0, tempo.MetronomeMark(number = 120, referent = note.Note(type='quarter')))
    hb.makeNotation(inPlace=True, cautionaryNotImmediateRepeat=False)
    return hb
Example #6
0
    def testIfAbsolutelyNecessary(self):
        '''
        Beginning of test cases for if-absolutely-necessary.
        '''
        p = converter.parse('tinyNotation: 2/4 f#2 f2')
        last_note = p.recurse().notes.last()
        last_note.pitch.accidental = Accidental('natural')
        last_note.pitch.accidental.displayType = 'if-absolutely-necessary'
        p.makeAccidentals(inPlace=True)
        self.assertIs(last_note.pitch.accidental.displayStatus, False)

        p[stream.Measure].first().insert(0, key.KeySignature(-7))  # F-flat!
        p.makeAccidentals(inPlace=True, overrideStatus=True)
        self.assertIs(last_note.pitch.accidental.displayStatus, True)

        p[key.KeySignature].first().sharps = -5  # No effect on us.
        p.makeAccidentals(inPlace=True, overrideStatus=True)
        self.assertIs(last_note.pitch.accidental.displayStatus, False)

        p = converter.parse('tinyNotation: 2/4 F#4 f4')
        last_note = p.recurse().notes.last()
        last_note.pitch.accidental = Accidental('natural')
        last_note.pitch.accidental.displayType = 'if-absolutely-necessary'
        p.makeAccidentals(inPlace=True)
        self.assertIs(last_note.pitch.accidental.displayStatus, False)

        # F# in different octaves -- need one.
        last_note.pitch.accidental.set('sharp')
        p.makeAccidentals(inPlace=True, overrideStatus=True)
        self.assertIs(last_note.pitch.accidental.displayStatus, True)
Example #7
0
    def testAccidentalsCautionary(self):
        '''
        a nasty test provided by Jose Cabal-Ugaz about octave leaps,
        cautionaryNotImmediateRepeat=False
        and key signature conflicts.
        '''
        bm = converter.parse(
            "tinynotation: 4/4 fn1 fn1 e-8 e'-8 fn4 en4 e'n4").flatten()
        bm.insert(0, key.KeySignature(1))
        bm.makeNotation(inPlace=True, cautionaryNotImmediateRepeat=False)
        notes = bm[note.Note]
        self.assertEqual(notes[0].pitch.accidental.name, 'natural')  # Fn
        self.assertEqual(notes[0].pitch.accidental.displayStatus, True)
        self.assertEqual(notes[1].pitch.accidental.name, 'natural')  # Fn
        self.assertEqual(notes[1].pitch.accidental.displayStatus, True)
        self.assertEqual(notes[2].pitch.accidental.name, 'flat')  # E-4
        self.assertEqual(notes[2].pitch.accidental.displayStatus, True)
        self.assertEqual(notes[3].pitch.accidental.name, 'flat')  # E-5
        self.assertEqual(notes[3].pitch.accidental.displayStatus, True)
        self.assertEqual(notes[4].pitch.accidental.name, 'natural')  # En4
        self.assertEqual(notes[4].pitch.accidental.displayStatus, True)
        self.assertEqual(notes[5].pitch.accidental.name, 'natural')  # En4
        self.assertEqual(notes[5].pitch.accidental.displayStatus, True)

        self.assertIsNotNone(notes[6].pitch.accidental)  # En5
        self.assertEqual(notes[6].pitch.accidental.name, 'natural')
        self.assertEqual(notes[6].pitch.accidental.displayStatus, True)
Example #8
0
    def testExpandTurns(self):
        from music21 import note, stream, clef, key, meter
        p1 = stream.Part()
        m1 = stream.Measure()
        m2 = stream.Measure()
        p1.append(clef.TrebleClef())
        p1.append(key.Key('F', 'major'))
        p1.append(meter.TimeSignature('2/4'))
        n1 = note.Note('C5', type='half')
        turn0 = Turn()
        n1.expressions.append(turn0)
        n2 = note.Note('B4', type='quarter')
        n2.duration.dots = 1

        n2.expressions.append(InvertedTurn())
        m1.append(n1)
        m2.append(key.KeySignature(5))
        m2.append(n2)
        m2.append(note.Rest('eighth'))
        p1.append(m1)
        p1.append(m2)
        realized1 = realizeOrnaments(n1)
        realized2 = realizeOrnaments(n2)
        self.assertEqual('C5 D5 C5 B-4 C5', ' '.join(n.pitch.nameWithOctave for n in realized1))
        self.assertEqual('B4 A#4 B4 C#5 B4', ' '.join(n.pitch.nameWithOctave for n in realized2))
        self.assertEqual(realized1[0].quarterLength, 1.0)
        self.assertEqual(realized1[1].quarterLength, 0.25)
        self.assertEqual(realized2[0].quarterLength, 0.5)
        self.assertEqual(realized2[1].quarterLength, 0.25)

        turn0.quarterLength = 0.125
        realized1b = realizeOrnaments(n1)
        self.assertEqual(realized1b[0].quarterLength, 1.5)
        self.assertEqual(realized1b[1].quarterLength, 0.125)
Example #9
0
 def __init__(self, scaleValue='C', scaleMode='major'):
     try:
         foo = scaleModes[scaleMode]
         self.realizerScale = foo(scaleValue)
         self.keySig = key.KeySignature(key.pitchToSharps(scaleValue, scaleMode))
     except KeyError:
         raise FiguredBassScaleException('Unsupported scale type-> ' + scaleMode)
Example #10
0
    def realize(self, srcObj: 'music21.note.Note'):
        '''
        Realize a mordent.

        returns a three-element tuple.
        The first is a list of the two notes that the beginning of the note were converted to.
        The second is the rest of the note
        The third is an empty list (since there are no notes at the end of a mordent)

        >>> n1 = note.Note('C4')
        >>> n1.quarterLength = 0.5
        >>> m1 = expressions.Mordent()
        >>> m1.realize(n1)
        ([<music21.note.Note C>, <music21.note.Note B>], <music21.note.Note C>, [])


        Note: use one of the subclasses, not the GeneralMordent class

        >>> n2 = note.Note('C4')
        >>> n2.quarterLength = 0.125
        >>> m2 = expressions.GeneralMordent()
        >>> m2.realize(n2)
        Traceback (most recent call last):
        music21.expressions.ExpressionException: Cannot realize a mordent if I do not
            know its direction
        '''
        from music21 import key

        if self.direction != 'up' and self.direction != 'down':
            raise ExpressionException(
                'Cannot realize a mordent if I do not know its direction')
        if self.size == '':
            raise ExpressionException(
                'Cannot realize a mordent if there is no size given')
        if srcObj.duration.quarterLength == 0:
            raise ExpressionException(
                'Cannot steal time from an object with no duration')
        if srcObj.duration.quarterLength < self.quarterLength * 2:
            raise ExpressionException(
                'The note is not long enough to realize a mordent')

        remainderDuration = srcObj.duration.quarterLength - (
            2 * self.quarterLength)
        if self.direction == 'down':
            transposeInterval = self.size.reverse()
        else:
            transposeInterval = self.size
        mordNotes = []
        self.fillListOfRealizedNotes(srcObj, mordNotes, transposeInterval)

        currentKeySig = srcObj.getContextByClass(key.KeySignature)
        if currentKeySig is None:
            currentKeySig = key.KeySignature(0)

        for n in mordNotes:
            n.pitch.accidental = currentKeySig.accidentalByStep(n.step)
        remainderNote = copy.deepcopy(srcObj)
        remainderNote.duration.quarterLength = remainderDuration
        # TODO clear just mordent here...
        return (mordNotes, remainderNote, [])
Example #11
0
def generate_examples():
    output_dir = ".\\Examples\\"

    # Example 1 - cycle 2/7 for C major
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_cycle_pair(sc, tonic_triad, "2/7")
    cycle.insert(0, key.KeySignature(0))
    cycle.metadata = metadata.Metadata()
    cycle.metadata.title = "Example 1 - Cycle 2/7 in C Major"
    cycle.write("MusicXML", output_dir + "Example 1")

    # Example 2 - cycle 4/5 for D major
    sc = scale.MajorScale('D')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'D4',
                                                         'C5'))
    cycle = generate_cycle_pair(sc, tonic_triad, "4/5")
    cycle.insert(0, key.KeySignature(2))
    cycle.metadata = metadata.Metadata()
    cycle.metadata.title = "Example 2 - Cycle 4/5 in D Major"
    cycle.write("MusicXML", output_dir + "Example 2")

    # Example 3 - cycle 3/6 for A harmonic minor
    sc = scale.HarmonicMinorScale('A')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'A4',
                                                         'G5'))
    cycle = generate_cycle_pair(sc, tonic_triad, "3/6")
    cycle.insert(0, key.KeySignature(0))
    cycle.metadata = metadata.Metadata()
    cycle.metadata.title = "Example 3 - Cycle 3/6 in A Harmonic Minor"
    cycle.write("MusicXML", output_dir + "Example 3")

    # Example 4 - cycle 3/6 for C major but with drop 2 chords
    tonic = 'C'
    sc = scale.MajorScale(tonic)
    root = sc.pitchFromDegree(1)
    tonic_triad = chord.Chord([root, root.transpose(7), root.transpose(16)])
    cycle = generate_cycle_pair(sc,
                                tonic_triad,
                                "3/6",
                                voicing_type=Voicing.Drop2_A_form)
    cycle.insert(0, key.KeySignature(0))
    cycle.metadata = metadata.Metadata()
    cycle.metadata.title = "Example 4 - Cycle 3/6 in C Major\nDrop 2 voicings"
    cycle.write("MusicXML", output_dir + "Example 4")
Example #12
0
def happyBirthday():
    hb = tinyNotation.TinyNotationStream\
        ("d8. d16 e4 d g f#2 d8. d16 e4 d a g2 "
         "d8. d16 d'4 b g8. g16 f#4 e c'8. c'16 b4 g a g2", "3/4")
    hb.insert(0, key.KeySignature(1))
    hb.insert(0, tempo.TempoText("Brightly"))
    hb.insert(0, tempo.MetronomeMark(number = 120, referent = note.QuarterNote()))
    hb.makeNotation(inPlace=True, cautionaryNotImmediateRepeat=False)
    return hb
Example #13
0
    def realize(self, srcObject):
        '''
        realize an appoggiatura
        
        returns a three-element tuple.
        The first is the notes that the grace note was converted to.
        The second is the rest of the note
        The third is an empty list (since there are no notes at the end of an appoggiatura)


        
        >>> n1 = note.Note("C4")
        >>> n1.quarterLength = 0.5
        >>> a1 = expressions.Appoggiatura()
        >>> a1.realize(n1)
        (<music21.note.Note D>, <music21.note.Note C>, [])
        
        
        >>> n2 = note.Note("C4")
        >>> n2.quarterLength = 1
        >>> a2 = expressions.HalfStepInvertedAppoggiatura()
        >>> a2.realize(n2)
        (<music21.note.Note B>, <music21.note.Note C>, [])
        
        '''
        from music21 import key
        if self.direction != 'up' and self.direction != 'down':
            raise ExpressionException(
                "Cannot realize an Appoggiatura if I do not know its direction"
            )
        if self.size == "":
            raise ExpressionException(
                "Cannot realize an Appoggiatura if there is no size given")
        if srcObject.duration == None or srcObject.duration.quarterLength == 0:
            raise ExpressionException(
                "Cannot steal time from an object with no duration")

        newDuration = srcObject.duration.quarterLength / 2
        if self.direction == "down":
            transposeInterval = self.size
        else:
            transposeInterval = self.size.reverse()

        appogNote = copy.deepcopy(srcObject)
        appogNote.duration.quarterLength = newDuration
        appogNote.transpose(transposeInterval, inPlace=True)

        remainderNote = copy.deepcopy(srcObject)
        remainderNote.duration.quarterLength = newDuration

        currentKeySig = srcObject.getContextByClass(key.KeySignature)
        if currentKeySig is None:
            currentKeySig = key.KeySignature(0)

        #TODO clear just mordent here...
        return (appogNote, remainderNote, [])
Example #14
0
 def __init__(self, scaleValue, scaleMode='major'):
     '''
     Constructs a FiguredBassScale object, with a scaleValue (key) and a scaleMode (major is default).
     '''
     self._scaleValue = convertToPitch(
         scaleValue)  #If scale value provided as string, convert to pitch
     self._scaleMode = scaleMode
     self._keySig = key.KeySignature(
         key.pitchToSharps(self._scaleValue, self._scaleMode))
     self._scale = self._constructScale()
Example #15
0
    def generateBassLine(self):
        '''
        Generates the bass line as a :class:`~music21.stream.Score`.

        >>> from music21.figuredBass import realizer
        >>> from music21 import key
        >>> from music21 import meter
        >>> from music21 import note
        >>> fbLine = realizer.FiguredBassLine(key.Key('B'), meter.TimeSignature('3/4'))
        >>> fbLine.addElement(note.Note('B2'))
        >>> fbLine.addElement(note.Note('C#3'), '6')
        >>> fbLine.addElement(note.Note('D#3'), '6')
        >>> #_DOCS_SHOW fbLine.generateBassLine().show()

        .. image:: images/figuredBass/fbRealizer_bassLine.*
            :width: 200


        >>> from music21 import corpus
        >>> sBach = corpus.parse('bach/bwv307')
        >>> sBach['bass'].measure(0).show('text')
        {0.0} ...
        {0.0} <music21.clef.BassClef>
        {0.0} <music21.key.Key of B- major>
        {0.0} <music21.meter.TimeSignature 4/4>
        {0.0} <music21.note.Note B->
        {0.5} <music21.note.Note C>

        >>> fbLine = realizer.figuredBassFromStream(sBach['bass'])
        >>> fbLine.generateBassLine().measure(1).show('text')
        {0.0} <music21.clef.BassClef>
        {0.0} <music21.key.KeySignature of 2 flats>
        {0.0} <music21.meter.TimeSignature 4/4>
        {3.0} <music21.note.Note B->
        {3.5} <music21.note.Note C>
        '''
        bassLine = stream.Part()
        bassLine.append(clef.BassClef())
        bassLine.append(key.KeySignature(self.inKey.sharps))
        bassLine.append(copy.deepcopy(self.inTime))
        r = None
        if self._paddingLeft != 0.0:
            r = note.Rest(quarterLength=self._paddingLeft)
            bassLine.append(r)

        for (bassNote, unused_notationString) in self._fbList:
            bassLine.append(bassNote)

        bl2 = bassLine.makeNotation(inPlace=False,
                                    cautionaryNotImmediateRepeat=False)
        if r is not None:
            m0 = bl2.getElementsByClass('Measure')[0]
            m0.remove(m0.getElementsByClass('Rest')[0])
            m0.padAsAnacrusis()
        return bl2
Example #16
0
    def keySignatureFromKeySign(self, keySign):
        # noinspection PyShadowingNames
        '''
        Returns a :class:`~music21.key.KeySignature` object from a keySign tag.

        >>> ci = capella.fromCapellaXML.CapellaImporter()
        >>> keySign = ci.domElementFromText('<keySign fifths="-1"/>')
        >>> ci.keySignatureFromKeySign(keySign)
        <music21.key.KeySignature of 1 flat>
        '''
        if 'fifths' in keySign.attrib:
            keyFifths = int(keySign.attrib['fifths'])
            return key.KeySignature(keyFifths)
Example #17
0
 def keySignatureFromKeySign(self, keySign):
     '''
     Returns a :class:`~music21.key.KeySignature` object from a keySign tag. 
     
     
     >>> ci = capella.fromCapellaXML.CapellaImporter()
     >>> keySign = ci.domElementFromText('<keySign fifths="-1"/>')
     >>> ci.keySignatureFromKeySign(keySign)
     <music21.key.KeySignature of 1 flat>
     '''
     if 'fifths' in keySign._attrs:
         keyFifths = int(keySign._attrs['fifths'].value)
         return key.KeySignature(keyFifths)
Example #18
0
def cycle36_drop2_a_minor_test():
    sc = scale.MinorScale('A')
    # tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'A4', 'G5'))
    triad_root = pitch.Pitch("A4")
    tonic_triad = chord.Chord(
        [triad_root,
         triad_root.transpose(7),
         triad_root.transpose(15)])
    cycle = generate_cycle_pair(sc,
                                tonic_triad,
                                "3/6",
                                voicing_type=Voicing.Drop2_A_form)
    cycle.insert(0, key.KeySignature(0))
    cycle.show()
Example #19
0
 def __init__(self, **fbLineOutputs):
     # fbLineOutputs always will have three elements, checks are for sphinx documentation only.
     if 'realizedSegmentList' in fbLineOutputs:
         self._segmentList = fbLineOutputs['realizedSegmentList']
     if 'inKey' in fbLineOutputs:
         self._inKey = fbLineOutputs['inKey']
         self._keySig = key.KeySignature(self._inKey.sharps)
     if 'inTime' in fbLineOutputs:
         self._inTime = fbLineOutputs['inTime']
     if 'overlayedParts' in fbLineOutputs:
         self._overlayedParts = fbLineOutputs['overlayedParts']
     if 'paddingLeft' in fbLineOutputs:
         self._paddingLeft = fbLineOutputs['paddingLeft']
     self.keyboardStyleOutput = True
Example #20
0
    def __init__(self):
        self.currentPart = None
        self.currentMeasure = None
        self.score = stream.Score()

        self.currentClef = "TREBLE"
        self.currentKey = key.KeySignature(0)

        self.withinSlur = False
        self.beginningSlurNote = None
        self.withinTie = False
        
        self.lyricPosition = 0
        self.lyrics = []

        self.activeAccidentals = {}
Example #21
0
 def xtestExpandTurns(self):
     from music21 import note, stream, clef, key, meter
     p1 = stream.Part()
     m1 = stream.Measure()
     m2 = stream.Measure()
     p1.append(clef.TrebleClef())
     p1.append(key.Key('F', 'major'))
     p1.append(meter.TimeSignature('2/4'))
     n1 = note.Note('C5', type='half')
     n1.expressions.append(Turn())
     n2 = note.Note('B4', type='half')
     n2.expressions.append(InvertedTurn())
     m1.append(n1)
     m2.append(key.KeySignature(5))
     m2.append(n2)
     p1.append(m1)
     p1.append(m2)
Example #22
0
def ch2_basic_I_A_1(show=True, *arguments, **keywords):
    '''p. 11
    For each of the melodies below, provide the correct meter signature.
    Next to the signature, write in the meter type (e.g. simple triple).
    '''
    from music21 import stream, key
    ex = stream.Stream()
    ex.insert(key.KeySignature(1))

    data = [
        [('d6', 1.5)],
        [('d6', 1.5)],
        [('d6', .5), ('c6', .5), ('b5', .5)],
        [('rest', .5), ('b5', .25), ('c6', .25), ('d6', .5)],
    ]

    for mData in data:
        m = stream.Measure()
        for p, d in mData:
            if p == 'rest':
                n = note.Rest()
            else:
                n = note.Note(p)
            n.quarterLength = d
            m.append(n)
        ex.append(m)

    # get the best time signature; make sure it agrees with the next
    # time signature, just to be sure
    ts1 = ex.getElementsByClass('Measure')[0].bestTimeSignature()
    ts2 = ex.getElementsByClass('Measure')[1].bestTimeSignature()

    # make sure these time signatures agree
    assert ts1.ratioEqual(ts2)
    for m in ex.getElementsByClass('Measure'):
        m.insert(0, copy.deepcopy(ts1))
    # append answers to first note
    ex.flat.notesAndRests[0].addLyric('Meter: %s' % ts1)
    ex.flat.notesAndRests[0].addLyric('Meter type: %s' % ts1.classification)

    if show:
        ex.show()
    else:
        unused_post = musicxml.m21ToXml.GeneralObjectExporter().parse(ex)
Example #23
0
def song():
    """
    Simple helper function that returns "Wlazł kotek na płotek" music stream
    """
    s = stream.Stream()
    ts1 = meter.TimeSignature("3/4")

    p1 = stream.Part(number=1)
    p1.insert(0, ts1)
    p1.insert(0, key.KeySignature(0))
    p1.insert(0, clef.TrebleClef())
    m1 = stream.Measure(number=1)
    m1.append(note.Note("G"))
    m1.append(note.Note("E"))
    m1.append(note.Note("E", type="quarter"))
    m2 = stream.Measure(number=2)
    m2.append(note.Note("F"))
    m2.append(note.Note("D"))
    m2.append(note.Note("D"))
    m3 = stream.Measure(number=3)
    m3.append(note.Note("C", type="eighth"))
    m3.append(note.Note("E", type="eighth"))
    m3.append(note.Note("G", type="half"))
    p1.append(m1)
    p1.append(m2)
    p1.append(m3)
    m4 = stream.Measure(number=4)
    m4.append(note.Note("G"))
    m4.append(note.Note("E"))
    m4.append(note.Note("E", type="quarter"))
    m5 = stream.Measure(number=5)
    m5.append(note.Note("F"))
    m5.append(note.Note("D"))
    m5.append(note.Note("D"))
    m6 = stream.Measure(number=6)
    m6.append(note.Note("C4", type="eighth"))
    m6.append(note.Note("E4", type="eighth"))
    m6.append(note.Note("C4", type="half"))
    p1.append(m4)
    p1.append(m5)
    p1.append(m6)
    s.insert(0, p1)
    return s
Example #24
0
def getMeasuresList(scores_json):
    scores = scores_json
    allMeasures = []
    lastMetronomeMark = tempo.MetronomeMark()
    lastKeysignature = key.KeySignature()
    lastTimeSignature = meter.TimeSignature()
    lastClef = clef.Clef()
    for i, strm in enumerate(scores):
        path = strm['path']
        strmScore = strm['score']
        for p in strmScore.getElementsByClass(stream.Part):
            for m in p.getElementsByClass(stream.Measure):
                isActive = False
                for r in m.recurse():
                    if type(r) == clef.TrebleClef:
                        lastClef = r
                    if type(r) == clef.BassClef:
                        lastClef = r
                    if type(r) == note.Note:
                        isActive = True
                    if type(r) == tempo.MetronomeMark:
                        lastMetronomeMark = r
                    if type(r) == key.KeySignature:
                        lastKeysignature = r
                    if type(r) == meter.TimeSignature:
                        lastTimeSignature = r
                try:
                    m.insert(0, lastTimeSignature)
                    m.insert(0, lastMetronomeMark)
                    m.insert(0, lastKeysignature)
                    m.insert(0, lastClef)
                except:
                    True
                if isActive:
                    obj = {
                        "path": path,
                        "part": p.partName,
                        "number": m.number,
                        "measure": m
                    }
                    allMeasures.append(obj)
    return allMeasures
Example #25
0
def ch2_writing_V_A(show=True, *arguments, **keywords):
    '''p. 18

    Using the meter signature given, add bar lines to the following melodies. 
    '''
    from music21 import key

    # note: tiny is not encoding C#s for c'#4 properly (it seems)
    ex = converter.parse("tinynotation: 3/2 g#1 f#4 g#4 a1 g#2 f#1 g#4. en8 g#2 f#4 r4 f#4 d#8 B8 e2 r4 e4 a4. a8 a2 g#4 g# b4. e8 a2~ a4 a4 d'n4. d'8 d'n2 c'#4 c'# c'# c'#")
    
    ex.insert(0, key.KeySignature(4))
    # presently, this only works if makeAccidentals is called before make measures
    ex.makeAccidentals(inPlace=True)
    ex = ex.makeMeasures() 
    ex.makeBeams(inPlace=True)

    if show:
        ex.show()
    else:
        unused_post = musicxml.m21ToString.fromMusic21Object(ex)
Example #26
0
def generate_readme_examples():
    # cycle 2
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle2matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()

    # cycle 3
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle3matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()

    # cycle 4
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle4matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()

    # cycle 5
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle5matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()

    # cycle 6
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle6matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()

    # cycle 7
    sc = scale.MajorScale('C')
    tonic_triad = chord.Chord(sc.pitchesFromScaleDegrees([1, 3, 5], 'C5',
                                                         'B5'))
    cycle = generate_full_cycle(sc, tonic_triad, cycle7matrix)[0]
    cycle.insert(0, key.KeySignature(0))
    cycle.show()
Example #27
0
    def parseList(self, dataList):
        r'''
        Parses a list where each element is a line from a nwctxt file.
        
        Returns a :class:`~music21.stream.Score` object
        
        
        
        >>> data = []
        >>> data.append("!NoteWorthyComposer(2.0)\n")
        >>> data.append("|AddStaff|\n")
        >>> data.append("|Clef|Type:Bass\n")
        >>> data.append("|TimeSig|Signature:4/4\n")
        >>> data.append("|Note|Dur:Whole|Pos:1\n")
        
        >>> 
        >>> nwt = noteworthy.translate.NoteworthyTranslator()
        >>> s = nwt.parseList(data)
        >>> s.show('text')
        {0.0} <music21.stream.Part ...>
            {0.0} <music21.stream.Measure 0 offset=0.0>
                {0.0} <music21.clef.BassClef>
                {0.0} <music21.meter.TimeSignature 4/4>
                {0.0} <music21.note.Note E>
    
        '''
        # Main
        for pi in dataList:
            pi = pi.rstrip()
            if pi.startswith('|') is False:
                continue
            sections = pi.split('|')
            command = sections[1]
            attributes = {}
            for attribute in sections[2:]:
                try:
                    (name, value) = attribute.split(':', 1)
                    attributes[name] = value
                except ValueError:
                    if attribute.strip() == "":
                        pass
                    else:
                        raise NoteworthyTranslateException(
                            "Cannot unpack value from %s in %s" %(attribute,pi))

            if command == "Note":  
                self.translateNote(attributes)
                self.lyricPosition += 1
            elif command == "Clef":
                self.createClef(attributes)
            elif command == "Rest":
                self.translateRest(attributes)
            elif command == "Key":
                self.createKey(attributes)
            elif command == "TimeSig":
                self.createTimeSignature(attributes)
            elif command == "Chord":
                self.translateChord(attributes)
                self.lyricPosition += 1
            elif command == "AddStaff":
                self.createPart()
                self.currentKey = key.KeySignature(0)
                self.activeAccidentals = {}
                self.lyrics = []
                self.lyricPosition = 0            
            elif command == "Lyric1":
                self.lyrics = self.createLyrics(attributes)
            elif command == "Bar":
                self.createBarlines(attributes)
            elif command == "Flow":
                self.currentMeasure = self.createOtherRepetitions(attributes)
            elif command == "DynamicVariance":
                self.createDynamicVariance(attributes)
            elif command == "Dynamic":
                self.createDynamics(attributes)
                    
        # Add the last Stuff 
        if len(self.currentMeasure) != 0:
            self.currentPart.append(self.currentMeasure)
        
        self.score.insert(0, self.currentPart)
        
        #print("SHOW")  
        #totalscore.show('text')
        #totalscore.show()
        return self.score
Example #28
0
    def realize(self, srcObject):
        '''
        realize a turn.
        
        returns a three-element tuple.
        The first is a list of the four notes that the beginning of the note was converted to.
        The second is a note of duration 0 because the turn "eats up" the whole note.
        The third is a list of the notes at the end if nachschlag is True, and empty list if False.

        >>> from  music21 import *
        >>> m1 = stream.Measure()
        >>> m1.append(key.Key('F', 'major'))
        >>> n1 = note.Note("C5")
        >>> m1.append(n1)
        >>> t1 = expressions.Turn()
        >>> t1.realize(n1)
        ([], <music21.note.Note C>, [<music21.note.Note D>, 
                                     <music21.note.Note C>, 
                                     <music21.note.Note B->, 
                                     <music21.note.Note C>])
        
        
        >>> m2 = stream.Measure()
        >>> m2.append(key.KeySignature(5))
        >>> n2 = note.Note("B4")
        >>> m2.append(n2)
        >>> t2 = expressions.InvertedTurn()
        >>> t2.realize(n2)
        ([], <music21.note.Note B>, [<music21.note.Note A#>, 
                                     <music21.note.Note B>, 
                                     <music21.note.Note C#>, 
                                     <music21.note.Note B>])

        
        
        >>> n2 = note.Note("C4")
        >>> n2.quarterLength = 0.125
        >>> t2 = expressions.Turn()
        >>> t2.realize(n2)
        Traceback (most recent call last):
            ...
        ExpressionException: The note is not long enough to realize a turn

        :type srcObj: base.Music21Object
        '''
        from music21 import key

        if self.size is None:
            raise ExpressionException("Cannot realize a turn if there is no size given")
        if srcObject.duration == None or srcObject.duration.quarterLength == 0:
            raise ExpressionException("Cannot steal time from an object with no duration")
        if srcObject.duration.quarterLength < 4 * self.quarterLength:
            raise ExpressionException("The note is not long enough to realize a turn")
        
        remainderDuration = srcObject.duration.quarterLength - 4 * self.quarterLength
        transposeIntervalUp = self.size
        transposeIntervalDown = self.size.reverse()
        turnNotes = []
        
        #TODO: if nachschlag...
        
        firstNote = copy.deepcopy(srcObject)
        #TODO: remove expressions
        firstNote.duration.quarterLength = self.quarterLength
        firstNote.transpose(transposeIntervalUp, inPlace = True)
        
        secondNote = copy.deepcopy(srcObject)
        #TODO: remove expressions
        secondNote.duration.quarterLength = self.quarterLength 
        
        thirdNote = copy.deepcopy(srcObject)
        #TODO: remove expressions
        thirdNote.duration.quarterLength = self.quarterLength
        thirdNote.transpose(transposeIntervalDown, inPlace = True)
        
        fourthNote = copy.deepcopy(srcObject)
        #TODO: remove expressions
        fourthNote.duration.quarterLength = self.quarterLength
    
        turnNotes.append(firstNote)
        turnNotes.append(secondNote)
        turnNotes.append(thirdNote)
        turnNotes.append(fourthNote)

        currentKeySig = srcObject.getContextByClass(key.KeySignature)
        if currentKeySig is None:
            currentKeySig = key.KeySignature(0)
       
        for n in turnNotes:
            n.accidental = currentKeySig.accidentalByStep(n.step)
            
        remainderNote = copy.deepcopy(srcObject)
        remainderNote.duration.quarterLength = remainderDuration
        
        return ([], remainderNote, turnNotes)
Example #29
0
    def realize(self, srcObj):
        '''
        realize a trill.
        
        returns a three-element tuple.
        The first is a list of the notes that the note was converted to.
        The second is None because the trill "eats up" the whole note.
        The third is a list of the notes at the end if nachschlag is True, and empty list if False.
        
        
        >>> n1 = note.Note("C4")
        >>> n1.quarterLength = 0.5
        >>> t1 = expressions.Trill()
        >>> t1.realize(n1)
        ([<music21.note.Note C>, 
          <music21.note.Note D>, 
          <music21.note.Note C>, 
          <music21.note.Note D>], None, [])
        
        
        >>> n2 = note.Note("D4")
        >>> n2.quarterLength = 0.125
        >>> t2 = expressions.Trill()
        >>> t2.realize(n2)
        Traceback (most recent call last):
            ...
        ExpressionException: The note is not long enough to realize a trill
        
        :type srcObj: base.Music21Object
        '''
        from music21 import key
        if self.size == "":
            raise ExpressionException("Cannot realize a trill if there is no size given")
        if srcObj.duration == None or srcObj.duration.quarterLength == 0:
            raise ExpressionException("Cannot steal time from an object with no duration")
        if srcObj.duration.quarterLength < 2*self.quarterLength:
            raise ExpressionException("The note is not long enough to realize a trill")
        if srcObj.duration.quarterLength < 4*self.quarterLength and self.nachschlag:
            raise ExpressionException("The note is not long enough for a nachschlag")
        
        transposeInterval = self.size
        transposeIntervalReverse = self.size.reverse()
        
        if self.nachschlag:
            numberOfTrillNotes = int(srcObj.duration.quarterLength / (self.quarterLength - 2))
        else:
            numberOfTrillNotes = int(srcObj.duration.quarterLength / self.quarterLength)
            
        trillNotes = []
        for unused_counter in range(int(numberOfTrillNotes / 2)):
            firstNote = copy.deepcopy(srcObj)
            #TODO: remove expressions
            firstNote.duration.quarterLength = self.quarterLength
            
            secondNote = copy.deepcopy(srcObj)
            #TODO: remove expressions
            secondNote.duration.quarterLength = self.quarterLength 
            secondNote.transpose(transposeInterval, inPlace = True)
        
            trillNotes.append(firstNote)
            trillNotes.append(secondNote)

        currentKeySig = srcObj.getContextByClass(key.KeySignature)
        if currentKeySig is None:
            currentKeySig = key.KeySignature(0)

        for n in trillNotes:
            n.accidental = currentKeySig.accidentalByStep(n.step)
        
        if self.nachschlag:
            firstNoteNachschlag = copy.deepcopy(srcObj)
            #TODO: remove expressions
            firstNoteNachschlag.duration.quarterLength = self.quarterLength
            firstNoteNachschlag.accidental = currentKeySig.accidentalByStep(
                                                        firstNoteNachschlag.step)
            
            secondNoteNachschlag = copy.deepcopy(srcObj)
            #TODO: remove expressions
            secondNoteNachschlag.duration.quarterLength = self.quarterLength
            secondNoteNachschlag.transpose(transposeIntervalReverse, 
                inPlace = True)
            secondNoteNachschlag.accidental = currentKeySig.accidentalByStep(
                                                        secondNoteNachschlag.step)
            
            nachschlag = [firstNoteNachschlag, secondNoteNachschlag]
            
            return (trillNotes, None, nachschlag)
        
        else:
            return (trillNotes, None, [])
Example #30
0
    def realize(self, srcObj):
        '''
        Realize a mordent.
        
        returns a three-element tuple.
        The first is a list of the two notes that the beginning of the note were converted to.
        The second is the rest of the note
        The third is an empty list (since there are no notes at the end of a mordent)
        
        >>> n1 = note.Note("C4")
        >>> n1.quarterLength = 0.5
        >>> m1 = expressions.Mordent()
        >>> m1.realize(n1)
        ([<music21.note.Note C>, <music21.note.Note B>], <music21.note.Note C>, [])
        
        
        Note: use one of the subclasses, not the GeneralMordent class
        
        >>> n2 = note.Note("C4")
        >>> n2.quarterLength = 0.125
        >>> m2 = expressions.GeneralMordent()
        >>> m2.realize(n2)
        Traceback (most recent call last):
        ExpressionException: Cannot realize a mordent if I do not know its direction

        :type srcObj: base.Music21Object
        '''
        from music21 import key
        
        if self.direction != 'up' and self.direction != 'down':
            raise ExpressionException("Cannot realize a mordent if I do not know its direction")
        if self.size == "":
            raise ExpressionException("Cannot realize a mordent if there is no size given")
        if srcObj.duration is None or srcObj.duration.quarterLength == 0:
            raise ExpressionException("Cannot steal time from an object with no duration")
        if srcObj.duration.quarterLength < self.quarterLength*2:
            raise ExpressionException("The note is not long enough to realize a mordent")

        remainderDuration = srcObj.duration.quarterLength - (2 * self.quarterLength)
        if self.direction == "down":
            transposeInterval = self.size.reverse()
        else:
            transposeInterval = self.size
        mordNotes = []
        
        firstNote = copy.deepcopy(srcObj)
        #firstNote.expressions = None
        #todo-clear lyrics.
        firstNote.duration.quarterLength = self.quarterLength
        secondNote = copy.deepcopy(srcObj)
        secondNote.duration.quarterLength = self.quarterLength
        #secondNote.expressions = None
        secondNote.transpose(transposeInterval, inPlace = True)
        
        mordNotes.append(firstNote)
        mordNotes.append(secondNote)
        
        currentKeySig = srcObj.getContextByClass(key.KeySignature)
        if currentKeySig is None:
            currentKeySig = key.KeySignature(0)

        for n in mordNotes:            
            n.accidental = currentKeySig.accidentalByStep(n.step)
        remainderNote = copy.deepcopy(srcObj)
        remainderNote.duration.quarterLength = remainderDuration
        #TODO clear just mordent here...
        return (mordNotes, remainderNote, [])