def simple3():
    '''
    reduce all measures of Chopin mazurkas to their rhythmic components and give the measure numbers (harder: render in notation) of all measures sorted by pattern.
    '''
    def lsort(keyname):
        return len(rhythmicHash[keyname])
    
    defaultPitch = music21.pitch.Pitch("C3")    
    
    import copy
    from music21.converter import parse
    from music21.stream import Stream, Measure
    
    
    #  semiFlat lets me get all Measures no matter where they reside in the tree structure
    measureStream = parse(testFiles.mazurka6).semiFlat[Measure]
    rhythmicHash = common.defHash(default = list, callDefault = True )

    for thisMeasure in measureStream:
        if not almostEquals(thisMeasure.duration.quarterLength, 3.0):
            continue
        notes = thisMeasure.flat.getNotes()
        rhythmicStream = Measure()
        
        offsetString = "" ## comma separated string of offsets 
        for thisNote in notes:
            rhythmNote = copy.deepcopy(thisNote)
            if rhythmNote.isNote:
                rhythmNote.pitch = defaultPitch
            elif rhythmNote.isChord:
                rhythmNote          = music21.note.Note()
                rhythmNote.pitch    = defaultPitch
                rhythmNote.duration = thisNote.duration
                            
            if not rhythmNote.isRest:
                offsetString += str(rhythmNote.offset) + ", "
            
            if thisNote.isChord:
                thisNote.pitch = defaultPitch
            rhythmicStream.append(rhythmNote)
            
        notes[0].lyric = str(thisMeasure.number)
        if len(rhythmicHash[offsetString]) == 0: # if it is our first encounter with the rhythm, add the rhythm alone in blue
            for thisNote in rhythmicStream:
                thisNote.color = "blue"
            rhythmicHash[offsetString].append(rhythmicStream)
        thisMeasure.getNotes()[0].editorial.comment.text = str(thisMeasure.number)
        rhythmicHash[offsetString].append(thisMeasure)

    allLily = lily.LilyString()
    allLily += meter.TimeSignature('3/4').lily + " "
    for thisRhythmProfile in sorted(rhythmicHash, key=lsort, reverse=True):
        for thisMeasure in rhythmicHash[thisRhythmProfile]:
            thisLily = " " + str(thisMeasure.bestClef().lily) + " " + str(thisMeasure.lily) + "\n"
            allLily += thisLily
    allLily.showPNG()
Example #2
0
    def insertKsTs(self, m: stream.Measure, ts: meter.TimeSignature,
                   ks: key.KeySignature):
        '''
        Insert a new time signature or key signature into measure m, if it's
        not already in the stream somewhere.
        '''
        if self.parent is None:
            m.timeSignature = ts
            m.keySignature = ks
            return

        if ts not in self.parent.tsList:
            m.timeSignature = ts
            self.parent.tsList.append(ts)
        if ks not in self.parent.ksList:
            m.keySignature = ks
            self.parent.tsList.append(ks)
    def notate_measure(self, previous_duration, bar, part):
        measure = Measure()
        if bar.tempo:
            mark = MetronomeMark(
                number=bar.tempo,
                referent=Duration(1)
            )
            measure.insert(0, mark)
            measure.leftBarline = 'double'
        if bar.duration != previous_duration:
            ts = TimeSignature('{}/4'.format(bar.duration))
            measure.timeSignature = ts

        # Fix Durations
        durations = [note['duration'] for note in part['notes']]

        components_list = split_at_beats(durations)
        components_list = [join_quarters(note_components) for note_components in components_list]
        for note, components in zip(part['notes'], components_list):
            note['durations'] = components

        # Notate
        for note in part['notes']:
            n = self.notate_note(note)
            measure.append(n)

        return measure
Example #4
0
def decode_score(encoding, num_measures, ts, image=False):
    score = Stream()
    score.timeSignature = TimeSignature(ts)
    steps_per_measure = len(encoding) / num_measures
    measure_ind = 0
    while measure_ind < num_measures:
        start_beat = int(measure_ind * steps_per_measure)
        end_beat = int((measure_ind + 1) * steps_per_measure)
        measure = Measure()
        for beat_ind in range(start_beat, end_beat):
            if image:
                played_pitches = np.nonzero(encoding[beat_ind])[0]
            else:
                played_pitches = np.nonzero(encoding[beat_ind])
            if len(played_pitches) == 0:
                measure.append(Rest(quarterLength=4.0 / GRANULARITY))
            else:
                played_notes = [
                    midi_to_note(int(pitch + MIN_PITCH))
                    for pitch in played_pitches
                ]
                chord = Chord(played_notes, quarterLength=4.0 / GRANULARITY)
                measure.append(chord)
        score.append(measure)
        measure_ind += 1
    return score
Example #5
0
    def m21(self):

        score = Score()
        part = Part()
        bars = len(self) // self.bar_size

        measure = Measure()
        measure.insert(0.0, self.meter.m21)

        for bar in range(bars):

            start = bar * self.bar_size
            end = (bar + 1) * self.bar_size
            positions = [position % self.bar_size 
                for position in self.iter_onset_positions(start=start, end=end)
            ]
            # Append an extra position to make sure that the last ioi is
            # between the last note and the end of the bar
            positions.append(self.bar_size)
            offsets = [self.get_offset(p) for p in positions]
            iois = [b - a for a, b in zip(offsets[:-1], offsets[1:])]

            for offset, ioi in zip(offsets[:-1], iois):

                note = Note('a5')
                note.duration.quarterLength = ioi * 4.0
                measure.insert(offset * 4.0, note)

            part.append(measure)
            measure = Measure()

        score.append(part)
        return score.makeMeasures()
    def __init__(self, ranges=False):
        score = self.score = Score()
        self.instruments = self.i = Instruments()
        self.parts = Parts(self.i)

        # Make Metadata
        timestamp = datetime.datetime.utcnow()
        metadata = Metadata()
        metadata.title = 'Short Stories'
        metadata.composer = 'Jonathan Marmor'
        metadata.date = timestamp.strftime('%Y/%m/%d')
        score.insert(0, metadata)

        [score.insert(0, part) for part in self.parts.l]
        score.insert(0, StaffGroup(self.parts.l))

        if ranges:
            # Don't make a piece, just show the instrument ranges
            for inst, part in zip(self.instruments.l, self.parts.l):
                measure = Measure()
                measure.timeSignature = TimeSignature('4/4')
                low = Note(inst.lowest_note)
                measure.append(low)
                high = Note(inst.highest_note)
                measure.append(high)
                part.append(measure)
            return

        self.duet_options = None

        # 8 to 12 minutes
        max_duration = 12
        piece_duration_minutes = scale(random.random(), 0, 1, 8, max_duration)

        # Make the "songs"
        self.songs = []
        total_minutes = 0
        n = 1
        while total_minutes < piece_duration_minutes - .75:
            print
            print 'Song', n
            song = Song(self, n)
            self.songs.append(song)
            print 'Song Duration:', int(round(song.duration_minutes * 60.0))
            print 'Tempo:', song.tempo
            print 'Number of Beats:', song.duration_beats

            n += 1
            total_minutes += song.duration_minutes

        _minutes, _seconds = divmod(total_minutes, 1.0)
        print
        print 'Total Duration: {}:{}'.format(int(_minutes), int(round(_seconds * 60)))
        print

        self.make_notation()
Example #7
0
 def __init__(self, ranges=False):
     if ranges:
         # Don't make a piece, just show the instrument ranges
         self.make_score()
         for inst, part in zip(self.instruments.l, self.parts.l):
             measure = Measure()
             measure.timeSignature = TimeSignature('4/4')
             low = Note(inst.lowest_note)
             measure.append(low)
             high = Note(inst.highest_note)
             measure.append(high)
             part.append(measure)
     else:
         # Make the piece
         self.make_score()
         self.choose_piece_duration()
         self.make_movements()
         self.choose_when_quarter_tones_start()
         self.fix_rhythm_notation()
Example #8
0
    def __init__(self, n, piece, movement, quadlet, couplet, lines):
        self.n = n
        self.piece = piece
        self.movement = movement
        self.quadlet = quadlet
        self.couplet = couplet
        self.lines = lines
        self.duration = quadlet.phrase_duration

        self.first = False
        if n == 1 and couplet.n == 1:
            self.first = True

        for line in lines:
            # print ('.' * int(line['rhythm'][0] * 2)) + ('-' * int(line['rhythm'][1] * 2)) + ('.' * int(line['rhythm'][2] * 2))
            part = piece.parts.d[line['instrument']]

            measure = Measure()
            if self.first and quadlet.previous_phrase_duration != self.duration:
                ts = TimeSignature('{}/4'.format(self.duration), self.duration)

                # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                # for i, b in enumerate(ts.beatSequence):
                #     if b.duration.quarterLength == 4:
                #         ts.beatSequence[i] = b.subdivide(2)
                #         # ts.beatSequence[i][0] = b.subdivide(2)
                #         # ts.beatSequence[i][1] = b.subdivide(2)
                #     elif b.duration.quarterLength == 3:
                #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                #     elif b.duration.quarterLength == 2:
                #         ts.beatSequence[i] = b.subdivide(2)
                measure.timeSignature = ts

            r1_dur, note_dur, r2_dur = line['rhythm']

            line['notes'] = []

            if r1_dur > 0:
                line['notes'].append({
                    'duration': r1_dur,
                    'pitch': 'rest'
                })

            line['notes'].append({
                'duration': note_dur,
                'pitch': line['pitch']
            })

            if r2_dur > 0:
                line['notes'].append({
                    'duration': r2_dur,
                    'pitch': 'rest'
                })

            self.fix_durations(line['notes'])

            for note in line['notes']:
                if note['pitch'] == 'rest':
                    n = Rest()
                else:
                    p = Pitch(note['pitch'])
                    # Force all flats
                    if p.accidental.name == 'sharp':
                        p = p.getEnharmonic()
                    n = Note(p)

                    # TODO add slurs
                    # TODO add glissandos
                    # TODO add -50 cent marks

                d = Duration()
                d.fill(note['durations'])
                n.duration = d

                measure.append(n)


            # if r1_dur > 0:
            #     r1 = Rest()
            #     r1.duration = Duration(r1_dur)
            #     measure.append(r1)

            # p = Pitch(line['pitch'])
            # # Force all flats
            # if p.accidental.name == 'sharp':
            #     p = p.getEnharmonic()

            # note = Note(p)
            # note.duration = Duration(note_dur)
            # measure.append(note)

            # if r2_dur > 0:
            #     r2 = Rest()
            #     r2.duration = Duration(r2_dur)
            #     measure.append(r2)


            part.append(measure)

        # Put full measure rests in instruments that aren't playing
        playing = [line['instrument'] for line in lines]
        resting = [i for i in piece.instruments.names if i not in playing]

        for i in resting:
            # print '.' * self.duration * 2
            part = piece.parts.d[i]

            measure = Measure()
            if self.first and quadlet.previous_phrase_duration != self.duration:
                ts = TimeSignature('{}/4'.format(self.duration), self.duration)

                # ts.beatSequence.subdivideNestedHierarchy(3)

                # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                # for i, b in enumerate(ts.beatSequence):
                #     if b.duration.quarterLength == 4:
                #         ts.beatSequence[i] = b.subdivide(2)
                #         # ts.beatSequence[i][0] = b.subdivide(2)
                #         # ts.beatSequence[i][1] = b.subdivide(2)
                #     elif b.duration.quarterLength == 3:
                #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                #     elif b.duration.quarterLength == 2:
                #         ts.beatSequence[i] = b.subdivide(2)
                measure.timeSignature = ts

            r = Rest()
            r.duration = Duration(self.duration)
            measure.append(r)

            # fixed_measure = measure.sliceByBeat()
            # part.append(fixed_measure)

            part.append(measure)
Example #9
0
def tensors_to_stream(outputs, config, metadata=None):
    cur_measure_number = 0
    parts = {}
    for part_name in outputs.keys():
        if part_name == 'extra':
            continue
        part = Part(id=part_name)
        parts[part_name] = part

    last_time_signature = None
    cur_time_signature = '4/4'
    for step in range(outputs['soprano'].shape[0]):
        extra = outputs['extra'][step]
        if extra[indices_extra['has_time_signature_3/4']].item() == 1:
            cur_time_signature = '3/4'
        elif extra[indices_extra['has_time_signature_4/4']].item() == 1:
            cur_time_signature = '4/4'
        elif extra[indices_extra['has_time_signature_3/2']].item() == 1:
            cur_time_signature = '3/2'
        cur_time_pos = extra[indices_extra['time_pos']].item()
        has_fermata = extra[indices_extra['has_fermata']].item() == 1

        if cur_time_pos == 1.0 or cur_measure_number == 0:
            for part_name, part in parts.items():
                part.append(Measure(number=cur_measure_number))
                if cur_measure_number == 0:
                    if part_name in ['soprano', 'alto']:
                        part[-1].append(clef.TrebleClef())
                    else:
                        part[-1].append(clef.BassClef())
                    key = int(
                        torch.argmax(
                            outputs['extra'][0, indices_extra['has_sharps_0']:
                                             indices_extra['has_sharps_11'] +
                                             1],
                            dim=0).item())
                    if key >= 6:
                        key -= 12
                    part[-1].append(KeySignature(key))
                    part[-1].append(MetronomeMark(number=90))
            cur_measure_number += 1

        if last_time_signature is None or cur_time_signature != last_time_signature:
            for part in parts.values():
                part[-1].append(TimeSignature(cur_time_signature))
            last_time_signature = cur_time_signature

        for part_name, part in parts.items():
            idx = torch.argmax(outputs[part_name][step]).item()
            if idx == indices_parts['is_continued']:
                try:
                    last_element = part[-1].flat.notesAndRests[-1]
                    cur_element = deepcopy(last_element)
                    if last_element.tie is not None and last_element.tie.type == 'stop':
                        last_element.tie = Tie('continue')
                    else:
                        last_element.tie = Tie('start')
                    cur_element.tie = Tie('stop')
                except IndexError:
                    logging.debug(
                        'Warning: "is_continued" on first beat. Replaced by rest.'
                    )
                    cur_element = Rest(quarterLength=config.time_grid)
                part[-1].append(cur_element)
            elif idx == indices_parts['is_rest']:
                part[-1].append(Rest(quarterLength=config.time_grid))
            else:
                pitch = Pitch()
                part[-1].append(Note(pitch, quarterLength=config.time_grid))
                # Set pitch value AFTER appending to measure in order to avoid unnecessary accidentals
                pitch.midi = idx + min_pitches[part_name] - len(indices_parts)

        if has_fermata:
            for part in parts.values():
                fermata = Fermata()
                fermata.type = 'upright'
                part[-1][-1].expressions.append(fermata)

    score = Score()
    if metadata is not None:
        score.append(Metadata())
        score.metadata.title = f"{metadata.title} ({metadata.number})"
        score.metadata.composer = f"Melody: {metadata.composer}\nArrangement: BachNet ({datetime.now().year})"
    for part in parts.values():
        part[-1].rightBarline = 'light-heavy'

    score.append(parts['soprano'])
    if 'alto' in parts:
        score.append(parts['alto'])
        score.append(parts['tenor'])
    score.append(parts['bass'])

    score.stripTies(inPlace=True, retainContainers=True)

    return score
def populate_measures(song):
    # Initial values
    time_signature_length = util.time_signature(song)
    seen_length = 0
    bars = []
    current_bar = []

    # Helper functions

    # Appends an item to a bar
    def append_bar(current_bar, seen_length, item):
        current_bar += [item]
        seen_length += item.duration.quarterLength
        return (current_bar, seen_length)

    # Checks to see if the item finishes the bar
    def check_bar(bars, current_bar, seen_length):
        if seen_length >= time_signature_length:
            bars += [current_bar]
            current_bar = []
            seen_length = 0
        return (bars, current_bar, seen_length)

    # Finds the notes
    def find_bars(part):
        if isinstance(part, Iterable):
            for item in part:
                if type(item) is Note:
                    return part
                else:
                    res = find_bars(item)
                    if res is not None:
                        return res
        return None

    # Find the part which has the notes
    part = find_bars(song)
    # Search through each item in the bar
    for item in part:
        if type(item) is Note:
            # Note
            (current_bar, seen_length) = append_bar(current_bar, seen_length,
                                                    item)
            (bars, current_bar,
             seen_length) = check_bar(bars, current_bar, seen_length)
        elif type(item) is Rest:
            # Rest
            (current_bar, seen_length) = append_bar(current_bar, seen_length,
                                                    item)
            (bars, current_bar,
             seen_length) = check_bar(bars, current_bar, seen_length)

    # LilyPond might forget a rest at the end
    if time_signature_length - seen_length > 0:
        (current_bar, seen_length) = append_bar(
            current_bar, seen_length,
            Rest(quarterLength=time_signature_length - seen_length))
    (bars, current_bar, seen_length) = check_bar(bars, current_bar,
                                                 seen_length)

    # Populate song.elements, which is where the items should have been
    song.elements = []
    for bar in bars:
        measure = Measure()
        for n in bar:
            measure.append(copy.deepcopy(n))
        song.append(measure)
    return song
Example #11
0
    key_name = key.step.upper() if key.mode == "major" else key.step.lower()

    for note in notes:
      if note.part == key.part and note.measure == key.measure:
        note.step = Interval(noteStart=Note(Key(key_name).asKey().tonic), noteEnd=note._music21_object).semitones % 12

  return notes


if __name__ == "__main__":
  """
  How to create Mupix Objects.
  """
  from music21.stream import Score, Part, Measure
  from music21.key import KeySignature
  from music21.note import Note  # noqa

  s = Score()
  p1 = Part(id="part1")
  m1 = Measure(number=1)
  m1.append(KeySignature(3))
  m1.append(Note("C4", type="eighth"))
  m2 = Measure(number=2)
  m2.append(KeySignature(0))
  m2.append(Note("G4", type="eighth"))
  p1.append([m1, m2])
  s.append([p1])

  notes = [NoteObject(item, 1) for item in s.recurse().notes if not item.isChord]
  print(notes)
Example #12
0
    def __init__(self, ranges=False):
        score = self.score = Score()
        self.instruments = self.i = Instruments()
        self.parts = Parts(self.i)


        # Make Metadata
        timestamp = datetime.datetime.utcnow()
        metadata = Metadata()
        metadata.title = 'Early Montreal'
        metadata.composer = 'Jonathan Marmor'
        metadata.date = timestamp.strftime('%Y/%m/%d')
        score.insert(0, metadata)

        [score.insert(0, part) for part in self.parts.l]
        score.insert(0, StaffGroup(self.parts.l))

        if ranges:
            # Don't make a piece, just show the instrument ranges
            for inst, part in zip(self.instruments.l, self.parts.l):
                measure = Measure()
                measure.timeSignature = TimeSignature('4/4')
                low = Note(inst.lowest_note)
                measure.append(low)
                high = Note(inst.highest_note)
                measure.append(high)
                part.append(measure)
            return


        # 18 to 21 minutes
        piece_duration_minutes = scale(random.random(), 0, 1, 18, 21)

        # Make the "songs"
        songs = []
        total_minutes = 0
        n = 1
        while total_minutes < piece_duration_minutes:
            print 'Song {}'.format(n)
            n += 1
            song = Song(self)
            songs.append(song)
            total_minutes += song.duration_minutes

        # Make notation
        previous_duration = None
        for song in songs:
            for bar in song.bars:
                for part in bar.parts:
                    measure = Measure()
                    if bar.tempo:
                        measure.insert(0, MetronomeMark(number=bar.tempo, referent=Duration(1)))
                        measure.leftBarline = 'double'
                    if bar.duration != previous_duration:
                        ts = TimeSignature('{}/4'.format(bar.duration))
                        measure.timeSignature = ts

                    # Fix Durations
                    durations = [note['duration'] for note in part['notes']]

                    components_list = split_at_beats(durations)
                    components_list = [join_quarters(note_components) for note_components in components_list]
                    for note, components in zip(part['notes'], components_list):
                        note['durations'] = components


                    for note in part['notes']:
                        if note['pitch'] == 'rest':
                            n = Rest()
                        if isinstance(note['pitch'], list):
                            pitches = []
                            for pitch_number in note['pitch']:
                                p = Pitch(pitch_number)
                                # Force all flats
                                if p.accidental.name == 'sharp':
                                    p = p.getEnharmonic()
                                pitches.append(p)
                            n = Chord(notes=pitches)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks


                        else:
                            p = Pitch(note['pitch'])
                            # Force all flats
                            if p.accidental.name == 'sharp':
                                p = p.getEnharmonic()
                            n = Note(p)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        d = Duration()
                        if note['duration'] == 0:
                            d.quarterLength = .5
                            d = d.getGraceDuration()
                        else:
                            d.fill(note['durations'])
                        n.duration = d

                        measure.append(n)

                    self.parts.d[part['instrument_name']].append(measure)
                previous_duration = bar.duration
Example #13
0
def generate(tune, clef=m21.clef.TrebleClef()):
    score = m21utils.loadScoreForTune(tune)
    # print 'score', score
    s = score.parts[0].getElementsByClass("Measure")
    m21.harmony.realizeChordSymbolDurations(s)  ## Needed to make this work!
    MyScore = m21.stream.Score()
    MyScore.append(s[0].keySignature)  ## get key from document
    MyScore.append(clef)  #add clef

    for m in s:
        MyMeasure = Measure()  ## Make a measure and put everything inside it
        MyMeasure.number = m.number  ## give the measure a number
        MyMeasure.rightBarline = m.rightBarline
        MyMeasure.leftBarline = m.leftBarline
        # print("_____________________")
        # print("In measure "+ str(m.number) + "(" + str(m.id) + ")" +" of " + str(len(s)) ) #debug monitoring
        c = m.getElementsByClass(ChordSymbol)
        for x in range(len(c)):
            # print(c[x].duration)
            # print(c[x].beat)
            # print (c[x].figure)
            # print("--------------------")
            TheFigure = c[x].figure
            MyChord = Chord(c[x].pitches)
            MySymbol = ChordSymbol()
            ######## Fix XML chord symbols ############
            if (TheFigure.find(" alter b9") != -1):
                MySymbol = m21utils.writeFlatNine(MyMeasure,
                                                  c[x].pitches[0].name,
                                                  c[x].duration,
                                                  c[x].chordKind)
            elif (TheFigure.find(" add b9") != -1):
                MySymbol = m21utils.writeFlatNine(MyMeasure,
                                                  c[x].pitches[0].name,
                                                  c[x].duration,
                                                  c[x].chordKind)
            elif (TheFigure.find(" add #9") != -1):
                MySymbol = m21utils.writeSharpNine(MyMeasure,
                                                   c[x].pitches[0].name,
                                                   c[x].duration,
                                                   c[x].chordKind)
            elif (TheFigure.find(" add #7") != -1):
                MySymbol = m21utils.writeSharpSeven(MyMeasure,
                                                    c[x].pitches[0].name,
                                                    c[x].duration,
                                                    c[x].chordKind)
            elif (TheFigure.find(" add #11") != -1):
                MySymbol = m21utils.writeSharpEleven(MyMeasure,
                                                     c[x].pitches[0].name,
                                                     c[x].duration,
                                                     c[x].chordKind)
            elif (TheFigure.find(" add b13") != -1):
                MySymbol = m21utils.writeFlatThirteen(MyMeasure,
                                                      c[x].pitches[0].name,
                                                      c[x].duration,
                                                      c[x].chordKind)
            elif (TheFigure.find(" add b6") != -1):
                MySymbol = m21utils.writeFlatSix(MyMeasure,
                                                 c[x].pitches[0].name,
                                                 c[x].duration, c[x].chordKind)
            elif (TheFigure.find(" alter b5") != -1):
                MySymbol = m21utils.writeHalfDim(MyMeasure,
                                                 c[x].pitches[0].name,
                                                 c[x].duration, c[x].chordKind)
            elif (TheFigure.find(" alter #5") != -1):
                MySymbol = m21utils.writeSharpFive(MyMeasure,
                                                   c[x].pitches[0].name,
                                                   c[x].duration,
                                                   c[x].chordKind)
            elif (TheFigure.find("pedal") != -1):
                MySymbol = m21utils.writePedal(MyMeasure, c[x].pitches[0].name,
                                               c[x].duration, c[x].chordKind)
            else:
                if (c[x].duration.type != "zero"):
                    if (c[x].root().name != c[x].bass().name):
                        # print (c[x].root().name, c[x].bass().name)
                        MySymbol = ChordSymbol(root=c[x].root(),
                                               bass=c[x].bass(),
                                               kind=c[x].chordKind)
                    else:
                        MySymbol = ChordSymbol(root=c[x].root(),
                                               bass=c[x].root(),
                                               kind=c[x].chordKind)
                        MySymbol.duration = c[x].duration
                        MyMeasure.append(MySymbol)
                        # print("Wrote chord " + str(MySymbol.figure) + "...")
            n3 = Note(MySymbol.third)
            n3.duration = Duration(c[x].duration.quarterLength * 0.50)
            # n3.lyric = '3rd'
            n3.octave = 5
            MyMeasure.append(n3)
            if (MySymbol.containsSeventh()):
                n7 = m21.note.Note(MySymbol.seventh)
                n7.duration = Duration(c[x].duration.quarterLength * 0.50)
                # n7.lyric = '7th'
                n7.octave = 5
                MyMeasure.append(n7)
            else:
                n5 = m21.note.Note(MySymbol.root())
                n5.duration = Duration(c[x].duration.quarterLength * 0.50)
                # n5.lyric = 'R'
                n5.octave = 5
                MyMeasure.append(n5)
            if ((m.number) % 4 == 0):
                sl = m21.layout.SystemLayout(isNew=True)
                MyMeasure.append(sl)
        MyScore.append(MyMeasure)

    # Set metadata
    title = tune + ' - Guide Tone Study'
    MyScore.metadata = m21.metadata.Metadata()
    MyScore.metadata.title = title
    MyScore.metadata.movementName = ' '  # For some reason this works, None and '' don't...
    MyScore.metadata.composer = 'Greg Pascale'

    return MyScore
Example #14
0
    def __init__(self, ranges=False):
        score = self.score = Score()
        self.instruments = self.i = Instruments()
        self.parts = Parts(self.i)

        # Make Metadata
        timestamp = datetime.datetime.utcnow()
        metadata = Metadata()
        metadata.title = 'Early Montreal'
        metadata.composer = 'Jonathan Marmor'
        metadata.date = timestamp.strftime('%Y/%m/%d')
        score.insert(0, metadata)

        [score.insert(0, part) for part in self.parts.l]
        score.insert(0, StaffGroup(self.parts.l))

        if ranges:
            # Don't make a piece, just show the instrument ranges
            for inst, part in zip(self.instruments.l, self.parts.l):
                measure = Measure()
                measure.timeSignature = TimeSignature('4/4')
                low = Note(inst.lowest_note)
                measure.append(low)
                high = Note(inst.highest_note)
                measure.append(high)
                part.append(measure)
            return

        # 18 to 21 minutes
        piece_duration_minutes = scale(random.random(), 0, 1, 18, 21)

        # Make the "songs"
        songs = []
        total_minutes = 0
        n = 1
        while total_minutes < piece_duration_minutes:
            print 'Song {}'.format(n)
            n += 1
            song = Song(self)
            songs.append(song)
            total_minutes += song.duration_minutes

        # Make notation
        previous_duration = None
        for song in songs:
            for bar in song.bars:
                for part in bar.parts:
                    measure = Measure()
                    if bar.tempo:
                        measure.insert(
                            0,
                            MetronomeMark(number=bar.tempo,
                                          referent=Duration(1)))
                        measure.leftBarline = 'double'
                    if bar.duration != previous_duration:
                        ts = TimeSignature('{}/4'.format(bar.duration))
                        measure.timeSignature = ts

                    # Fix Durations
                    durations = [note['duration'] for note in part['notes']]

                    components_list = split_at_beats(durations)
                    components_list = [
                        join_quarters(note_components)
                        for note_components in components_list
                    ]
                    for note, components in zip(part['notes'],
                                                components_list):
                        note['durations'] = components

                    for note in part['notes']:
                        if note['pitch'] == 'rest':
                            n = Rest()
                        if isinstance(note['pitch'], list):
                            pitches = []
                            for pitch_number in note['pitch']:
                                p = Pitch(pitch_number)
                                # Force all flats
                                if p.accidental.name == 'sharp':
                                    p = p.getEnharmonic()
                                pitches.append(p)
                            n = Chord(notes=pitches)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        else:
                            p = Pitch(note['pitch'])
                            # Force all flats
                            if p.accidental.name == 'sharp':
                                p = p.getEnharmonic()
                            n = Note(p)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        d = Duration()
                        if note['duration'] == 0:
                            d.quarterLength = .5
                            d = d.getGraceDuration()
                        else:
                            d.fill(note['durations'])
                        n.duration = d

                        measure.append(n)

                    self.parts.d[part['instrument_name']].append(measure)
                previous_duration = bar.duration
Example #15
0
    def __init__(self, number, piece, movement):
        self.number = number
        self.piece = piece
        self.movement = movement

        instrument_opts = piece.instruments.names[:]

        self.note_opts = {}
        for name in instrument_opts:
            self.note_opts[name] = piece.i.d[name].all_notes

        form = self.form = song_forms.choose()

        self.duration = len(form) * 4

        self.type = 'solo'
        if number % 2:
            self.type = 'ensemble'

        if self.type == 'solo':
            if len(movement.solo_ensemble_options) == 0:
                movement.solo_ensemble_options = piece.i.get_unison_ensembles(min_notes=6)
                print 'Hey, we ran out of unison ensembles! Cool!'
            solo_ensemble_hash = random.choice(movement.solo_ensemble_options.keys())
            self.soloists = movement.solo_ensemble_options[solo_ensemble_hash]['instruments']
            self.soloist_names = [s.nickname for s in self.soloists]
            self.soloists_shared_notes = movement.solo_ensemble_options[solo_ensemble_hash]['notes']
            # Remove chosen ensemble from options
            del movement.solo_ensemble_options[solo_ensemble_hash]

            # remove chosen soloists from instrument options for the song
            for soloist in self.soloist_names:
                instrument_opts.remove(soloist)

            self.accompanist_names = instrument_opts

            len_accompanists = len(self.accompanist_names)
            if len_accompanists == 2:
                ensemble_size = 2
            elif len_accompanists == 3:
                ensemble_size = random.choice([2, 3])
            elif len_accompanists == 4:
                ensemble_size = random.choice([1, 2, 3, 4])

            self.accompanist_names = random.sample(self.accompanist_names, ensemble_size)


        else:
            # who plays, who sits out?
            # ensemble_size = weighted_choice([3, 4, 5, 6], [1, 4, 5, 4])
            # self.ensemble_names = random.sample(instrument_opts, ensemble_size)

            # Everyone plays
            self.ensemble_names = instrument_opts


        # make a phrase for each unique part of the form (eg, an `a` in `abacabac`)
        unique_phrases = []
        for f in set(form):
            if self.type == 'solo':
                PhraseClass = SoloPhrase
            elif self.type == 'ensemble':
                PhraseClass = EnsemblePhrase
            unique_phrases.append(PhraseClass(piece, movement, self))

        # Copy the phrases in the order specified by form
        phrases = []
        for f in form:
            phrases.append(unique_phrases[f])

        # Render phrases as music21 objects
        for phrase in phrases:
            for part in phrase.parts:
                measure = Measure()
                if movement.first_measure:
                    ts = TimeSignature('4/4')

                    # ts.beatSequence = ts.beatSequence.subdivide(4)
                    ts.beamSequence = ts.beamSequence.subdivide(4)


                    # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                    # for i, b in enumerate(ts.beatSequence):
                    #     if b.duration.quarterLength == 4:
                    #         ts.beatSequence[i] = b.subdivide(2)
                    #         # ts.beatSequence[i][0] = b.subdivide(2)
                    #         # ts.beatSequence[i][1] = b.subdivide(2)
                    #     elif b.duration.quarterLength == 3:
                    #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                    #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                    #     elif b.duration.quarterLength == 2:
                    #         ts.beatSequence[i] = b.subdivide(2)




                    measure.timeSignature = ts

                    # ts.getBeams()

                self.fix_durations(part['notes'])

                for note in part['notes']:
                    if note['pitch'] == 'rest':
                        n = Rest()
                    else:
                        p = Pitch(note['pitch'])
                        # Force all flats
                        if p.accidental.name == 'sharp':
                            p = p.getEnharmonic()
                        n = Note(p)

                        # TODO add slurs
                        # TODO add glissandos
                        # TODO add -50 cent marks

                    d = Duration()
                    d.fill(note['durations'])
                    n.duration = d

                    measure.append(n)

                # if len(measure.notesAndRests) > 1:
                #     measure.sliceByBeat(inPlace=True)

                # measure.makeBeams(inPlace=True)

                piece.parts.d[part['instrument_name']].append(measure)
            movement.first_measure = False