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
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
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()
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()
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()
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)
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
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)
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
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
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
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