def testColorCapuaFicta(self): from music21.note import Note from music21.stream import Stream (n11, n12, n13, n14) = (Note(), Note(), Note(), Note()) (n21, n22, n23, n24) = (Note(), Note(), Note(), Note()) n11.duration.type = "quarter" n11.name = "D" n12.duration.type = "quarter" n12.name = "E" n13.duration.type = "quarter" n13.name = "F" n14.duration.type = "quarter" n14.name = "G" n21.name = "C" n21.duration.type = "quarter" n22.name = "C" n22.duration.type = "quarter" n23.name = "B" n23.octave = 3 n23.duration.type = "quarter" n24.name = "C" n24.duration.type = "quarter" stream1 = Stream() stream1.append([n11, n12, n13, n14]) stream2 = Stream() stream2.append([n21, n22, n23, n24]) ### Need twoStreamComparer to Work evaluateWithoutFicta(stream1, stream2) assert n13.editorial.harmonicInterval.name == "d5", n13.editorial.harmonicInterval.name evaluateCapuaTwoStreams(stream1, stream2) colorCapuaFicta(stream1, stream2, "both") assert n13.editorial.harmonicInterval.name == "P5", n13.editorial.harmonicInterval.name
def generate_scale_tone(notes: [], count): items = [ 'C', 'D', 'E', 'F', 'G', 'A', 'B', 'C#', 'D#', 'F#', 'G#', 'A#' ] rand_item = items[random.randrange(len(items))] scales = scale.MajorScale(rand_item) all_pitches = list(set([pitch for pitch in scales.getPitches()])) all_note_names = [i.name for i in all_pitches] note_name = random.choice(all_note_names) final_note = Note(note_name) duration_list = [1, 1 / 2] if not notes: final_note.duration.quarterLength = random.choice(duration_list) return final_note try: if notes[count - 1].duration.quarterLength == 1 / 2 and notes[ count - 2].duration.quarterLength != 1 / 2: final_note.duration.quarterLength = 1 / 2 return final_note except: if count == 0: final_note.duration.quarterLength = 1 / 2 return final_note else: pass else: final_note.duration.quarterLength = random.choice(duration_list) return final_note
def chord_search(notes, candidates): """Attempt to find the best chord to match a set of notes""" best_chord, best_score = C_MAJ, 1000 for chord in candidates: chord_score = 0 for note1 in chord.notes: note1 = Note(note1) for note2 in notes: chromatic_distance = notesToChromatic(note1, note2).semitones # Normalize distance to be between 0 and 6 chromatic_distance = chromatic_distance % 12 if chromatic_distance > 6: chromatic_distance = 12 - chromatic_distance chord_score += CHROMATIC_PENALTY[chromatic_distance] if chord_score < best_score: best_score = chord_score best_chord = chord print(best_chord.name) return best_chord
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
from pianoplayer.wavegenerator import soundof from music21.note import Note soundof([Note("C5"), "E-5", Note("G5")], duration=1) soundof([Note("A4")], duration=1) ## OR (needs pygame) # from music21.midi.realtime import StreamPlayer # from music21.stream import Stream # s = Stream() # s.append(Note("C5")) # s.append(Note("E5")) # s.append(Note("G5")) # sp = StreamPlayer(s) # sp.play()
def generate(tune, clef=m21.clef.TrebleClef()): # Load in the score score = m21utils.loadScoreForTune(tune) # Some basic preprocessing / cleanup score.parts[0].removeByClass('Instrument') score.parts[0].partName = None m21.harmony.realizeChordSymbolDurations(score) ## Argh!!! # Go measure by measure and build the study measures = score.parts[0].getElementsByClass("Measure") for measure in measures: # print measure # Remove any existing notes in the measure (we're about to add our own) measure.removeByClass('Note') # Grab the list of chord symbols in this measure chordSymbols = measure.getElementsByClass( 'ChordSymbol').matchingElements() # Remove the chord symbols so we can add them back interleaved with the notes # we're about to add measure.removeByClass('ChordSymbol') # Add notes for each chord symbol for symbol in chordSymbols: measure.append(symbol) # print symbol.duration.quarterLength n3 = Note(symbol.third) n3.duration = Duration(symbol.duration.quarterLength * 0.50) n3.octave = 5 n3.lyric = '3' measure.append(n3) if (symbol.containsSeventh()): n7 = m21.note.Note(symbol.seventh) n7.duration = Duration(symbol.duration.quarterLength * 0.50) n7.lyric = '7' n7.octave = 5 measure.append(n7) else: n5 = m21.note.Note(symbol.root()) n5.duration = Duration(symbol.duration.quarterLength * 0.50) n5.lyric = 'R' n5.octave = 5 measure.append(n5) # TODO: don't think this is needed # if measure.number % 4 == 0: # measure.append(m21.layout.SystemLayout(isNew=True)) # for x in range(len(c)): # 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' score.metadata = m21.metadata.Metadata() score.metadata.title = title score.metadata.movementName = ' ' # For some reason this works, None and '' don't... score.metadata.composer = 'Greg Pascale' return score
from music21 import stream, instrument from music21.note import Note n = Note("A2", type='quarter') drumPart = stream.Part() drumPart.insert(0, instrument.Woodblock()) drumMeasure = stream.Measure() drumMeasure.append(n) drumPart.append(drumMeasure) # This line actually generate the midi on my mac but there is no relevant software to read it and the opening fail drumPart.show('midi')
def __init__(self, df, piece_filename, piece_descr_stub): self.df = df self.piece_filename = piece_filename self.phrase_number = df["common", "phrase"].iloc[0] self._run_sanity_checks() tenor_notes = self.df["tenor", "note"].dropna().apply( lambda n: n.nameWithOctave).unique() tenor_pcs = self.df["tenor", "pitch_class"].dropna().unique() if len(tenor_notes) != 1 or len(tenor_pcs) != 1: raise RuntimeError( f"[DDD] Missing or non-unique tenor PC: tenor_notes={tenor_notes}, tenor_pcs={tenor_pcs}, piece={self.piece_filename}, df={self.df}" ) self.tenor_note = Note(tenor_notes[0]) self.tenor_pc = tenor_pcs[0] # FIXME: adding the attribute 'final' is a hack; instead, we should call it 'reference_pc' # and also add reference_pc attributes to the other analysis input classes self.final = self.tenor_pc self.note_of_final = self.tenor_note s_duplum_notes = self.df[("duplum", "note")] if any(s_duplum_notes.isnull()): raise RuntimeError( "Some duplum notes in organum phrase are null: {}".format( s_duplum_notes)) self.duplum_notes = list(s_duplum_notes) self.duplum_note_pairs = [ NotePair(n1, n2) for n1, n2 in pairwise(self.duplum_notes) ] self.has_voice_crossing = any( [n < self.note_of_final for n in self.duplum_notes]) s_voice_crossing = self.df[("duplum", "note")] < self.note_of_final if s_voice_crossing.any(): self.offset_of_first_voice_crossing = s_voice_crossing.where( s_voice_crossing == True).dropna().index[0] self.idx_of_first_voice_crossing = s_voice_crossing.index.get_loc( self.offset_of_first_voice_crossing) else: # self.idx_of_first_voice_crossing = len(s_voice_crossing) self.offset_of_first_voice_crossing = s_voice_crossing.index[-1] + 1 self.idx_of_first_voice_crossing = len(s_voice_crossing) self.notes = list(s_duplum_notes[ s_duplum_notes.index < self.offset_of_first_voice_crossing]) self.pitch_classes = [PC.from_note(n) for n in self.notes] self.note_pairs = [NotePair(n1, n2) for n1, n2 in pairwise(self.notes)] self.mode_degrees = [ ModeDegree.from_note_pair(note=n, base_note=self.note_of_final) for n in self.notes ] self.pc_pairs = list(zip(self.pitch_classes, self.pitch_classes[1:])) self.mode_degree_pairs = list( zip(self.mode_degrees, self.mode_degrees[1:])) # # self.notes = list(self.df["duplum", "note"]) # # self.pitch_classes = [PC.from_note(n) for n in self.notes] # self.mode_degrees = [ModeDegree.from_note_pair(note=n, base_note=self.note_of_final) for n in self.notes] # self.pc_pairs = list(zip(self.pitch_classes, self.pitch_classes[1:])) # # self.note_pairs = [NotePair(n1, n2) for (n1, n2) in zip(self.notes, self.notes[1:])] # self.mode_degree_pairs = list(zip(self.mode_degrees, self.mode_degrees[1:])) # self.lowest_note = min(self.notes) # self.ambitus = calculate_ambitus(self) # self._melodic_outline_candidates = calculate_melodic_outline_candidates(self.notes, self.note_pairs) self._melodic_outline_candidates = calculate_melodic_outline_candidates( self.duplum_notes, self.duplum_note_pairs, before_idx=self.idx_of_first_voice_crossing) if not df["common", "phrase"].isnull().any(): # FIXME: the only reason the phrase numbers can be null here is because we use this class # when constructing the organum piece dataframe in calculate_dataframe_from_music21_stream(). # The values should only be null the first time around, and should be non-null the second time. # However, this is really a hack and should be fixed properly. self.descr = f"{piece_descr_stub}.p{self.phrase_number:02d}.{self._measure_descr_short}"
def test_mode_degrees_from_note_pairs(): assert 1 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("D3")) assert 1 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("E3")) assert 1 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("F3")) assert 1 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("G3")) assert 1 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("A3")) assert 1 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("B3")) assert 1 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("C3")) assert 1 == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("B-3")) assert 2 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("D3")) assert 2 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("E3")) assert 2 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("F3")) assert 2 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("G3")) assert 2 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("A3")) assert 2 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("B3")) assert 2 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("C3")) assert 2 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("B-3")) assert "flat-2" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("A3")) assert 3 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("D3")) assert 3 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("E3")) assert 3 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("F3")) assert 3 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("G3")) assert 3 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("A3")) assert 3 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("B3")) assert 3 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("C3")) assert 3 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("B-3")) assert "flat-3" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("G3")) assert 4 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("D3")) assert 4 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("E3")) assert 4 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("F3")) assert 4 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("G3")) assert 4 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("A3")) assert 4 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("B3")) assert 4 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("C3")) assert 4 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("B-3")) assert "flat-4" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("F3")) assert 5 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("D3")) assert 5 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("E3")) assert 5 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("F3")) assert 5 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("G3")) assert 5 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("A3")) assert 5 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("B3")) assert 5 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("C3")) assert 5 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("B-3")) assert "flat-5" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("E3")) assert 6 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("D3")) assert 6 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("E3")) assert 6 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("F3")) assert 6 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("G3")) assert 6 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("A3")) assert 6 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("B3")) assert 6 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("C3")) assert 6 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("B-3")) assert "flat-6" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("D3")) assert 7 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("D3")) assert 7 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("E3")) assert 7 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("F3")) assert 7 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("G3")) assert 7 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("A3")) assert 7 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("B3")) assert 7 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("C3")) assert 7 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("B-3")) assert "flat-7" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("C3")) assert 1 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("D3")) assert "flat-2" == ModeDegree.from_note_pair(note=Note("E-3"), base_note=Note("D3")) assert 2 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("D3")) assert 3 == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("D3")) assert "#3" == ModeDegree.from_note_pair(note=Note("F#3"), base_note=Note("D3")) assert 4 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("D3")) assert 5 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("D3")) assert "flat-6" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("D3")) assert 6 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("D3")) assert 7 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("D3")) assert 1 == ModeDegree.from_note_pair(note=Note("F#3"), base_note=Note("F#3")) assert "flat-1" == ModeDegree.from_note_pair(note=Note("F3"), base_note=Note("F#3")) assert 2 == ModeDegree.from_note_pair(note=Note("G3"), base_note=Note("F#3")) assert 3 == ModeDegree.from_note_pair(note=Note("A3"), base_note=Note("F#3")) assert "flat-4" == ModeDegree.from_note_pair(note=Note("B-3"), base_note=Note("F#3")) assert 4 == ModeDegree.from_note_pair(note=Note("B3"), base_note=Note("F#3")) assert 5 == ModeDegree.from_note_pair(note=Note("C3"), base_note=Note("F#3")) assert 6 == ModeDegree.from_note_pair(note=Note("D3"), base_note=Note("F#3")) assert "flat-7" == ModeDegree.from_note_pair(note=Note("E-3"), base_note=Note("F#3")) assert 7 == ModeDegree.from_note_pair(note=Note("E3"), base_note=Note("F#3"))
def test_make_results_dataframe(): notes1 = [Note("A3"), Note("D3"), Note("C3"), Note("D3"), Note("E3")] notes2 = [ Note("F3"), Note("A3"), Note("G3"), Note("B-3"), Note("F3"), Note("C3"), Note("F3"), Note("B3") ] notes3 = [Note("F3"), Note("C3"), Note("A3"), Note("G3"), Note("A3")] piece1 = FakePiece(descr="piece_1", final="G", notes=notes1) piece2 = FakePiece(descr="piece_2", final="G", notes=notes2) piece3 = FakePiece(descr="piece_3", final="G", notes=notes3) items = [piece3, piece2, piece1] modal_category = ModalCategory(items, modal_category_type="final", key="G") from chantstats.v2.freqs import PCFreqs def calculate_relative_pc_freqs(item, unit): return PCFreqs.from_notes(item.notes).rel_freqs df = modal_category.make_results_dataframe( analysis_func=calculate_relative_pc_freqs, unit="pcs") row_piece1 = pd.Series([40.0, 0, 20.0, 0, 0, 0, 20.0, 0, 0, 20.0], index=list(PC)) row_piece2 = pd.Series([0, 0, 0, 37.5, 0, 12.5, 12.5, 12.5, 12.5, 12.5], index=list(PC)) row_piece3 = pd.Series([0, 0, 0, 20.0, 0, 20.0, 40.0, 0, 0, 20.0], index=list(PC)) df_expected = pd.DataFrame({ "piece_3": row_piece3, "piece_2": row_piece2, "piece_1": row_piece1 }).T assert_frame_equal(df_expected, df)
def test_6(): top, bot = _setup_parts() top.append(Note('G4', quarterLength=1.0)) bot.append(Note('G3', quarterLength=0.5)) bot.append(Note('A3', quarterLength=0.5)) return Score([top, bot])
def test_4(): top, bot = _setup_parts() top.append(Note('G4', quarterLength=0.25)) top.append(Rest(quarterLength=0.25)) bot.append(Note('G3', quarterLength=0.5)) return Score([top, bot])
def test_14(): top, bot = _setup_parts() top.append(Note('G4', quarterLength=0.0625)) top.append(Note('G4', quarterLength=0.0625)) # 0.0625 top.append(Note('G4', quarterLength=0.0625)) # 0.125 top.append(Note('G4', quarterLength=0.0625)) # 0.1875 top.append(Note('G4', quarterLength=0.0625)) # 0.25 top.append(Note('G4', quarterLength=0.0625)) # 0.3125 top.append(Note('G4', quarterLength=0.0625)) # 0.375 top.append(Note('G4', quarterLength=0.0625)) # 0.4375 top.append(Note('G4', quarterLength=0.5)) # 0.5 bot.append(Note('G3', quarterLength=0.125)) bot.append(Rest(quarterLength=0.125)) # 0.125 bot.append(Note('A3', quarterLength=0.125)) # 0.25 bot.append(Rest(quarterLength=0.0625)) # 0.375 bot.append(Rest(quarterLength=0.0625)) # 0.4375 bot.append(Note('G3', quarterLength=0.5)) # 0.5 return Score([top, bot])
def algorithm(melody, chords, debug=False): is_major = util.is_major(util.key(melody)) if is_major: unigrams = notes_major_unigrams bigrams = notes_major_bigrams trigrams = notes_major_trigrams tetragrams = notes_major_tetragrams given = notes_major_given given_2 = notes_2_major_given with_octaves_unigrams = notes_with_octaves_major_unigrams with_octaves_bigrams = notes_with_octaves_major_bigrams with_octaves_given = notes_with_octaves_major_given else: unigrams = notes_minor_unigrams bigrams = notes_minor_bigrams trigrams = notes_minor_trigrams tetragrams = notes_minor_tetragrams given = notes_minor_given given_2 = notes_2_minor_given with_octaves_unigrams = notes_with_octaves_minor_unigrams with_octaves_bigrams = notes_with_octaves_minor_bigrams with_octaves_given = notes_with_octaves_minor_given def square(prob): return prob * prob transposed_melody = util.notes_names(melody, util.key(melody)) # Viterbi algorithm (adapted for randomness) note_types = util.note_names # Unigrams V = [{}] for note_1 in note_types: V[0][note_1] = { 'prob': unigrams[note_1] * (given[note_1][transposed_melody[0]]) * given_2[note_1][chords[0]], 'prev': None } # Bigrams V.append({}) for note_2 in note_types: tr_probs = [(note_1, V[0][note_1]['prob'] * bigrams[note_1][note_2]) for note_1 in note_types] (n_1, max_tr_prob) = viterbi.rand_probability(tr_probs, mapping=square) V[1][note_2] = { 'prob': max_tr_prob * (given[note_2][transposed_melody[1]]) * given_2[note_2][chords[1]], 'prev': n_1 } # Trigrams V.append({}) for note_3 in note_types: tr_probs = [(note_2, V[1][note_2]['prob'] * trigrams[note_1][note_2][note_3]) for note_1 in note_types for note_2 in note_types] (n_2, max_tr_prob) = viterbi.rand_probability(tr_probs, mapping=square) V[2][note_3] = { 'prob': max_tr_prob * (given[note_3][transposed_melody[2]]) * given_2[note_3][chords[2]], 'prev': n_2 } # Tetragrams for t in range(3, len(chords)): V.append({}) for note_4 in note_types: tr_probs = [(note_3, V[t - 1][note_3]['prob'] * tetragrams[note_1][note_2][note_3][note_4]) for note_1 in note_types for note_2 in note_types for note_3 in note_types] (n_3, max_tr_prob) = viterbi.rand_probability( tr_probs, mapping=square ) if t != len(chords) - 1 else viterbi.max_probability(tr_probs) V[t][note_4] = { 'prob': max_tr_prob * (given[note_4][transposed_melody[t]]) * given_2[note_4][chords[t]], 'prev': n_3 } mel = viterbi.max_backtrace(V, debug=debug) # Viterbi algorithm (for octaves) # Unigrams V = [{}] for note_1 in [mel[0] + str(octave) for octave in range(0, 8)]: V[0][note_1] = {'prob': with_octaves_unigrams[note_1], 'prev': None} #V[0][note_1] = {'prob': with_octaves_unigrams[note_1] * (with_octaves_given[note_1][transposed_melody[0].nameWithOctave] + with_octaves_given[transposed_melody[0].nameWithOctave][note_1]), 'prev': None} # Bigrams for t in range(1, len(mel)): V.append({}) for note_2 in [mel[t] + str(octave) for octave in range(0, 8)]: tr_probs = [(note_1, V[t - 1][note_1]['prob'] * with_octaves_bigrams[note_1][note_2]) for note_1 in V[t - 1].keys()] (n_1, max_tr_prob) = viterbi.max_probability(tr_probs) V[t][note_2] = {'prob': max_tr_prob, 'prev': n_1} #V[t][note_2] = {'prob': max_tr_prob * (with_octaves_given[note_1][transposed_melody[t].nameWithOctave] + with_octaves_given[transposed_melody[t].nameWithOctave][note_1]), 'prev': n_1} mel = viterbi.max_backtrace(V, debug=debug) mel = [Note(note_name) for note_name in mel] mel = util.notes_names(mel, util.key(melody), reverse=True, include_octave=True) return mel
def test_calculate_ambitus(): piece = Mock(lowest_note=Note("D3"), note_of_final=None) assert calculate_ambitus(piece) == "undefined" piece = Mock(lowest_note=Note("C3"), note_of_final=Note("E3")) assert calculate_ambitus(piece) == "authentic" piece = Mock(lowest_note=Note("D3"), note_of_final=Note("G3")) assert calculate_ambitus(piece) == "plagal" piece = Mock(lowest_note=Note("F3"), note_of_final=Note("F4")) assert calculate_ambitus(piece) == "plagal" # with pytest.raises(Exception, match="We expect the lowest note to be less than an octave below the main final"): # piece = Mock(lowest_note=Note("D3"), note_of_final=Note("G4")) # calculate_ambitus(piece) # # with pytest.raises(Exception, match="We expect the lowest note to be less than an octave below the main final"): # piece = Mock(lowest_note=Note("F4"), note_of_final=Note("C3")) # calculate_ambitus(piece) piece = Mock(lowest_note=Note("D3"), note_of_final=Note("G4")) assert calculate_ambitus(piece) == "undefined" piece = Mock(lowest_note=Note("F4"), note_of_final=Note("C3")) assert calculate_ambitus(piece) == "undefined"
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 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 PlayFlute(self, m): if m == 1: f = Note("A----", type='whole') elif m == 2: f = Note("A---", type='whole') elif m == 3: f = Note("A--", type='whole') elif m == 4: f = Note("A-`", type='whole') elif m == 5: f = Note("A-", type='whole') elif m == 6: f = Note("A`", type='whole') elif m == 7: f = Note("A~", type='whole') elif m == 8: f = Note("B", type='whole') elif m == 9: f = Note("B##", type='whole') elif m == 10: f = Note("B####", type='whole') elif m == 11: f = Note("B#5", type='whole') elif m == 12: f = Note("B#6", type='whole') FlutePart = stream.Part() FlutePart.insert(0, instrument.PanFlute()) fluteMeasure = stream.Measure() fluteMeasure.append(f) FlutePart.append(fluteMeasure) sp = midi.realtime.StreamPlayer(FlutePart) sp.play()
os.chdir('.') # set working directory loop = 10 length = 0.5 # Highest octave, volume gets lower shepard_tone_u = stream.Part() shepard_tone_u.insert(0, instrument.Piano()) c_major = [ 'C#5', 'D#5', 'E#5', 'F#5', 'G#5', 'A#5', 'B#5', 'C#6', 'D#6', 'E#6', 'F#6', 'G#6', 'A#6', 'B#6' ] for l in range(loop): volume_increment = 0 for i in c_major: n = Note(i, quarterLength=length) n.volume.velocityScalar = 0.7 - volume_increment shepard_tone_u.append(n) volume_increment = volume_increment + 0.05 # Middle octave, volume constant shepard_tone_m = stream.Part() shepard_tone_m.insert(0, instrument.Piano()) c_major = [ 'C#3', 'D#3', 'E#3', 'F#3', 'G#3', 'A#3', 'B#3', 'C#4', 'D#4', 'E#4', 'F#4', 'G#4', 'A#4', 'B#4' ] for l in range(loop): for i in c_major: n = Note(i, quarterLength=length) shepard_tone_m.append(n)
def from_figure(cls, figure: str) -> 'SpotifyChord': # if figure of type Xkind/X- : build it from an other enharmonic as bass if len(figure.split('/')) > 1 and list(figure)[0] == list( figure.split('/')[1])[0]: return SpotifyChord.from_figure( list(figure)[0] + '/' + Note(list(figure.split( '/')[1])[0]).pitch.getAllCommonEnharmonics()[0].name) #if figure == 'Am/A-': # return SpotifyChord(bass='A-', root='A', kind='minor') #if figure == 'E7/E-': # return SpotifyChord(bass='E-', root='E', kind='dominant-seventh') if figure == 'NC': return SpotifyChord(spotify_figure='NC') root, structure, bass = split(figure) spotify_figure = None if structure in [ '', '+', '7+', '7+ add 9', 'dim', 'add 2', 'add 4', '7 add 11', 'm add 2', 'm7 add 4', 'm add 4', 'maj7', 'M7', 'M9', 'M11', 'M13', '/o7', 'o7', 'm', 'm6', 'm7', 'm9', 'm11', 'm13', '6', '7', '9', '11', '13', 'sus', 'sus2', 'sus4', 'sus add 7', 'm add 9', 'm7 add 9', 'm7 add 11', '6 add 9', 'm6 add 9', 'pedal', 'power' ]: # explicit_figure = figure explicit_figure = root + structure + bass elif structure == '9 alter b5': explicit_figure = root + bass + '9b5' elif structure == '7 alter b5': explicit_figure = root + bass + '7b5' elif structure == '7 alter #5': explicit_figure = root + bass + '7#5' elif structure == 'm7 alter b5': explicit_figure = root + bass + '/o7' elif structure == '7 add 4 subtract 3': explicit_figure = root + bass + 'sus add 7' elif structure == 'sus add 7 add 9': # TODO Check if the 7th should be diminished explicit_figure = root + bass + ',45b79' spotify_figure = root + bass + '9sus4 ' elif structure == 'sus add 7 add 13': # TODO Check if the 7th should be diminished # Pitches are not in the right order explicit_figure = root + bass + ',45b713' spotify_figure = root + bass + 'sus4 add7 add13' elif structure == 'sus add 7 add 9 add 13': # TODO Check if the 7th should be diminished # Pitches are not in the right order explicit_figure = root + bass + ',45b7913' spotify_figure = root + bass + 'sus4 add7 add9 add13' elif structure == 'sus add 7 add b9': # TODO Check if the 7th should be diminished explicit_figure = root + bass + ',45b7b9' spotify_figure = root + bass + 'b9sus4 ' elif structure == 'sus add 7 add 9 add 11 add 13': explicit_figure = root + bass + ',45791113' spotify_figure = root + bass + '13sus4 ' elif structure == 'pedal': explicit_figure = root + bass + 'pedal' elif structure == '7 add #11': explicit_figure = root + bass + '7 #11' elif structure == '7 alter #5 add #9': explicit_figure = root + bass + '+7 #9' elif structure == '9 alter #5': explicit_figure = root + bass + '9 #5' elif structure == 'm alter #5': explicit_figure = root + bass + 'm #5' elif structure == '7 alter b5 add b9': explicit_figure = root + bass + '7 b5b9' elif structure == 'm7 alter #5': explicit_figure = root + bass + 'm7 #5' elif structure == '7 alter b5 add #9': explicit_figure = root + bass + '7 b5#9' elif structure == '7 add b9': explicit_figure = root + bass + '7 b9' elif structure == '7 add #9': explicit_figure = root + bass + '7 #9' elif structure == '9 add #11': explicit_figure = root + bass + '9 #11' elif structure == '7 add b13': explicit_figure = root + bass + '7 b13' elif structure == '7 add #9 add #11': explicit_figure = root + bass + '7 #9#11' elif structure == '7 add b9 add b13': explicit_figure = root + bass + '7 b9b13' elif structure == 'add 9': explicit_figure = root + bass + 'add9' elif structure == 'maj7 add #11': explicit_figure = root + bass + 'maj7 #11' elif structure == 'sus add b9 add b9': explicit_figure = root + bass + 'sus b9' elif structure == 'm7 add b9': explicit_figure = root + bass + 'm7 b9' elif structure == 'add #11': explicit_figure = root + bass + ',#11' elif structure == '7 subtract 5 add b9 add #9 add #11 add b13': # TODO Pitches are not in the correct order explicit_figure = root + bass + ',3b7b9#9#11b13' spotify_figure = root + bass + '7 -5 b9 #9 #11 b13' elif structure == '13 alter b5': explicit_figure = root + bass + '13b5' elif structure == 'alter b5': explicit_figure = root + bass + ',b5' elif structure == 'maj7 alter #5': explicit_figure = root + bass + 'maj7 #5' elif structure == 'maj7 alter b5': explicit_figure = root + bass + 'maj7 b5' elif structure == '7 alter #5 add b9': explicit_figure = root + bass + '+7 b9' elif structure == '7 alter #5 add #9 add #11': explicit_figure = root + bass + '+7 #9#11' elif structure == '7+ add b9': explicit_figure = root + bass + '+7 b9' elif structure == '7 add #9 add b13': explicit_figure = root + bass + '7 #9b13' elif structure == 'M9 add #11': explicit_figure = root + bass + 'M9 #11' elif structure == 'M9 alter b5': explicit_figure = root + bass + 'M9 b5' elif structure == '7 add #11 add b9 add #5': explicit_figure = root + bass + '+7 b9#11' elif structure in ['7+ add #9', '7 add #9 alter #5']: explicit_figure = root + bass + '+7 #9' elif structure == 'm11 alter b5': explicit_figure = root + bass + 'm11 b5' elif structure == 'bpedal': # TODO This is a hack, replacing the 'b' by a '-' explicit_figure = root + bass + '-pedal' elif structure in ['13 add #11', '13 alter #11']: # TODO Check if a better solution exists # 1) This chord should be 13 alter #11 # 2) The order of the pitches is wrong explicit_figure = root + bass + ',35b7913#11' spotify_figure = '13 alter #11' elif structure in ['13 add b9', '13 alter b9']: # TODO Check if a better solution exists # 1) This chord should be 13 alter #11 # 2) The order of the pitches is wrong explicit_figure = root + bass + ',35b7b91113' spotify_figure = '13 alter b9' elif structure in ['13 add b9', '13 alter b9']: # TODO Check if a better solution exists # 1) This chord should be 13 alter #11 # 2) The order of the pitches is wrong explicit_figure = root + bass + ',35b7b91113' spotify_figure = '13 alter b9' elif structure == '13 subtract 5 subtract 11': # TODO Check if a better solution exists # 1) This chord should be 13 alter #11 # 2) The order of the pitches is wrong explicit_figure = root + bass + ',3b7913' spotify_figure = '13 sus4 omit 11' elif structure == 'm9 alter b5': explicit_figure = root + bass + 'm9 b5' elif structure == '7 subtract 5': explicit_figure = root + bass + '7 omit5' elif structure == 'pedal add 5': explicit_figure = root + bass + 'omit3' else: raise ValueError('unknown chord symbol ' + root + bass + structure) return SpotifyChord(spotify_figure=spotify_figure, figure=explicit_figure, bass=bass, root=root)
def test(): stream = Stream() n1 = Note('C4', duration=Duration(1.5)) n2 = Note('D4', duration=Duration(0.5)) n3 = Note('E4') n4 = Note('F4') n5 = Note('G4') n6 = Note('A4') n7 = Note('C4') n8 = Note('D4').getGrace() n9 = Note('E4').getGrace() n10 = Note('F4') n11 = Note('G4') n12 = Note('A4', duration=Duration(0.5)) n13 = Note('A4', duration=Duration(0.5)) gliss1 = Glissando([n2, n3]) gliss2 = Glissando([n5, n6]) gliss3 = Glissando([n6, n7]) gliss4 = Glissando([n8, n9]) slur1 = Slur([n2, n3]) slur2 = Slur([n6, n7]) slur3 = Slur([n9, n10]) stream.append([n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13]) stream.insert(0, gliss1) stream.insert(0, gliss2) stream.insert(0, gliss3) stream.insert(0, gliss4) stream.insert(0, slur1) stream.insert(0, slur2) stream.insert(0, slur3) return stream
import numpy as np from music21.note import Note from .pitch_class import PC from .mode_degree import ModeDegree from .note_pair import NotePair from .plainchant_sequence_piece import PlainchantSequencePiece __all__ = ["make_random_notes", "FakePhrase"] candidate_notes = [ Note("D3"), Note("E3"), Note("F3"), Note("G3"), Note("A3"), Note("B3"), Note("C4"), Note("D4"), Note("E4"), Note("F4"), Note("G4"), Note("A4"), Note("B4"), ] def make_random_notes(num, seed): np.random.seed(seed) return list(np.random.choice(candidate_notes, size=num))
TASK_DIR = '/Users/faraaz/workspace/apollo/task_1/data/' CORPUS_DIR = '/Users/faraaz/workspace/apollo/data/xml/' COMPOSERS = ['bach', 'beethoven'] COMPOSER_TO_ERA = { 'bach': 'baroque', 'handel': 'baroque', 'beethoven': 'classical', 'mozart': 'classical', 'chopin': 'romantic', 'strauss': 'romantic' } MEASURES_PER_CUT = 16 MAX_NOTE = Note('C8') MIN_NOTE = Note('A0') MAX_PITCH = MAX_NOTE.pitches[0].midi MIN_PITCH = MIN_NOTE.pitches[0].midi assert MAX_PITCH == 108 assert MIN_PITCH == 21 NOTE_RANGE = int(MAX_PITCH - MIN_PITCH + 1) GRANULARITY = 16 STEPS_PER_CUT = 48 * 4 pruning_stats = { 'discarded_num_measures': set(), 'discarded_time_signature': set(), 'discarded_key_signature': set(), 'discarded_note_range': set(), 'discarded_num_parts': set(), 'discarded_granularity': set(),
from music21.instrument import fromString as get_instrument from music21.clef import BassClef timestamp = datetime.datetime.utcnow() metadata = Metadata() metadata.title = 'The Title' metadata.composer = 'Jonathan Marmor' metadata.date = timestamp.strftime('%Y/%m/%d') score = Score() score.insert(0, metadata) part = Part() parts = [part] oboe = get_instrument('oboe') part.insert(0, oboe) score.insert(0, part) score.insert(0, StaffGroup(parts)) for dur in [[1, .5], [.25], [.25, 2]]: pitch = Pitch(60) note = Note(pitch) duration = Duration() duration.fill(dur) note.duration = duration part.append(note) score.show('musicxml', '/Applications/Sibelius 7.5.app')
def get_midi_stream_1(): part1 = [Rest(), Rest(), Note('E-'), Rest()] part2 = [Rest(), Rest(), Note('A-'), Rest()] part3 = [Note('B-'), Rest(), Note('E-'), Rest()] part4 = [Note('B-'), Rest(), Note('A-'), Rest()] part5 = [Note('B-'), Rest(), Rest(), Rest()] part6 = [Note('G'), Rest(), Note('C'), Rest()] part7 = [Note('D'), Rest(), Note('E-'), Rest()] stream_instance = Stream() stream_instance.append(deepcopy(part1)) stream_instance.append(deepcopy(part2)) stream_instance.append(deepcopy(part3)) stream_instance.append(deepcopy(part2)) stream_instance.append(deepcopy(part3)) stream_instance.append(deepcopy(part2)) stream_instance.append(deepcopy(part4)) stream_instance.append(deepcopy(part5)) stream_instance.append(deepcopy(part1)) stream_instance.append(deepcopy(part6)) stream_instance.append(deepcopy(part7)) stream_instance.append(deepcopy(part6)) stream_instance.append(deepcopy(part7)) return stream_instance
def test_pitch_class_from_note(): assert "A" == PC.A == PC.from_note(Note("A4")) assert "B-" == PC.B_FLAT == PC.from_note(Note("B-3")) assert "G" == PC.G == PC.from_note(Note("G2"))