def notate_score(musician_names, instrument_names, music): score = Score() for musician_name, instrument_name in zip(musician_names, instrument_names): instrument = get_instrument(instrument_name) instrument.partName = instrument.instrumentName instrument.partAbbreviation = instrument.instrumentAbbreviation parts = [] part = Part() parts.append(part) part.insert(0, instrument) score.insert(0, part) score.insert(0, StaffGroup(parts)) notes = music[musician_name] for pitches in notes: if not pitches or pitches == 'stop': note = Rest() elif len(pitches) == 1: pitch = Pitch(pitches[0] + 60) note = Note(pitch) else: note = Chord(notes=[Pitch(p + 60) for p in pitches]) duration = Duration() duration.fill([4.0]) note.duration = duration part.append(note) score.show('musicxml', '/Applications/Sibelius 7.5.app')
def make_music21_score( part_names=('violin', 'flute', 'oboe', 'clarinet', 'alto_saxophone', 'trumpet', 'bass', 'percussion'), title='Title', composer='Jonathan Marmor', time_signature=None, starting_tempo_bpm=60, starting_tempo_quarter_duration=1.0, timestamp=None, ): if not timestamp: timestamp = datetime.datetime.utcnow() metadata = Metadata() metadata.title = title metadata.composer = composer metadata.date = timestamp.strftime('%Y/%m/%d') score = Score() score.insert(0, metadata) for part_name in part_names: instrument_name, instrument_number = parse_part_name(part_name) instrument = instrument_data[instrument_name] part = Part() metronome_mark = MetronomeMark( number=starting_tempo_bpm, referent=Duration(starting_tempo_quarter_duration)) part.append(metronome_mark) if time_signature: # Should be a string like '12/8' music21_time_signature = TimeSignature(time_signature) part.append(music21_time_signature) m21_instrument = instrument['class']() m21_instrument.partName = instrument['name'] m21_instrument.partAbbreviation = instrument['abbreviation'] if instrument_number > 1: m21_instrument.partName = '{} {}'.format(instrument['name'], instrument_number) m21_instrument.partAbbreviation = '{} {}'.format( instrument['abbreviation'], instrument_number) part.insert(0, m21_instrument) clef = instrument.get('clef') if clef: part.append(clef()) score.insert(0, part) return score
def setup_score(title, composer): timestamp = datetime.datetime.utcnow() metadata = Metadata() metadata.title = title metadata.composer = composer metadata.date = timestamp.strftime('%Y/%m/%d') score = Score() score.insert(0, metadata) return score
def generate_song(chord_length=15,show_symbols=False): '''Generate a random chord progression with a piano/bass comp and return as a Music21 score. Default length of 15 chord changes (plus the fixed ones at start/end) makes a score about one A4 page.''' # Start with a blank score score = Score() # TODO: Add swing rhythm indicator without having to do it manually # in musescore (how to with music21?) # Add tracks/intstruments - names etc will be set automatically piano = Part() piano.insert(0, Piano()) score.insert(0,piano) bass = Part() bass.insert(0, AcousticBass()) score.insert(0,bass) #hihat = Part() TODO drum kit # Get a random progression prog = ProgressionGenerator() prog.generate(chord_length) # Go through the progression, adding a comp for each chord for chord_choice in prog.chords: roman = RomanNumeral(chord_choice) # Convert string into a generic Roman I/IV/etc chord # Duration = eights until the next chord change. # at least 1 bar on "important" chords (I,IV,V) if chord_choice in ('Imaj7', 'IVmaj7', 'V7'): duration = random.choice((8,8,8,8,10,10,12,12,14,16)) else: # 1 bar or less on "minor" (pun intended) chords duration = random.choice((2,4,4,4,6,6,8,8,8,8)) add_piano_riff(roman, duration, piano, show_symbols) add_bass_walk(roman, duration, bass) # TODO drum part # ending riff on last bar or two duration = random.choice((8,8,16)) add_piano_closing(RomanNumeral('Imaj7'), duration, piano, show_symbols) add_bass_closing(RomanNumeral('Imaj7'), duration, bass) return score
def generate_counterpoint_attempt(): # Import the melody, and process it filename = sys.argv[1] song = transform.import_mid(filename) time_signature_symbol = util.time_signature_symbol(song) transform.populate_measures(song) # Compute a counterpoint melody original_melody, generate_melody = counterpoint.algorithm( song, time_signature_symbol) # Build a new score score = Score() score.insert(0, original_melody) score.insert(0, generate_melody) # Export the score transform.export_mid(score, filename + '_gcp') transform.export_ly(score, filename + '_gcp') transform.export_pdf(score, filename + '_gcp')
def write_notation_cell(music, path, event_index): score = Score() metadata = Metadata() metadata.title = '' metadata.composer = '' score.insert(0, metadata) layout = ScoreLayout() layout.scalingMillimeters = 1.25 layout.scalingTenths = 40 score.insert(0, layout) for musician in music: instrument_name = musician['instrument'] instrument = get_instrument(instrument_name) instrument.partName = instrument.instrumentName if instrument.instrumentName is 'Violoncello': instrument.partName = 'Cello' instrument.partAbbreviation = instrument.instrumentAbbreviation parts = [] part = Part() parts.append(part) part.insert(0, instrument) score.insert(0, part) # score.insert(0, StaffGroup(parts)) for event in musician['music']: pitches = event['pitches'] dur = event['duration'] # if not pitches or pitches == 'stop': # note = Rest() if len(pitches) == 1: pitch = Pitch(pitches[0] + 60) note = Note(pitch) else: note = Chord(notes=[Pitch(p + 60) for p in pitches]) duration = Duration() duration.fill([dur]) note.duration = duration part.append(note) file_path = os.path.join(path, str(event_index).zfill(2)) musicxml_file_path = file_path + '.xml' png_output_file_path = file_path + '.png' score.write('musicxml', musicxml_file_path) write_png_with_musescore(musicxml_file_path, png_output_file_path, dpi=600)
def predict(self, data, count, temp, length=500): songs = list(set([i.song for i in data])) bug = True while bug: try: condition = True while condition: try: random_song = random.choice(songs) slice_by_instrument = dict(zip(self.target_instruments_str, [[] for i in self.target_instruments_str])) for j in self.target_instruments_str: for i in data: if i.song == random_song and i.instrument == j: slice_by_instrument[j].append(i) slice_by_instrument_without_rests = dict(zip(self.target_instruments_str, [[] for i in self.target_instruments_str])) for i in slice_by_instrument.keys(): for song in slice_by_instrument[i]: if not isinstance(song.chords[0], note.Rest): slice_by_instrument_without_rests[i].append(song) if len(slice_by_instrument_without_rests[i]) != 0: slice_by_instrument[i] = random.choice(slice_by_instrument_without_rests[i]) else: slice_by_instrument[i] = random.choice(slice_by_instrument[i]) condition = False except IndexError: continue guitar_chords = slice_by_instrument['Electric Guitar'].chords guitar_durations = slice_by_instrument['Electric Guitar'].durations bass_chords = slice_by_instrument['Electric Bass'].chords drum_chords = slice_by_instrument['Piano'].chords starting_slice_notes = (np.asarray(encode_using_mapper(guitar_chords, self.guitar_mapper)) / len(self.guitar_mapper))[:20] starting_slice_durations = (np.asarray(encode_using_mapper(guitar_durations, self.guitar_durations_mapper)) / len( self.guitar_durations_mapper))[:20] starting_slice_bass = (np.asarray(encode_using_mapper(bass_chords, self.bass_mapper)) / len(self.bass_mapper))[:20] starting_slice_drum = (np.asarray(encode_using_mapper(drum_chords, self.drum_mapper)) / len(self.drum_mapper))[:20] songs_in_db_cnt = len(get_songs_by_author(self.db_name)) to_generate = count for j in range(songs_in_db_cnt, songs_in_db_cnt + to_generate): generated_output = generate_multi_instrument_notes(self.model, starting_slice_notes, starting_slice_durations, starting_slice_bass, starting_slice_drum, self.guitar_mapper, self.guitar_durations_mapper, self.bass_mapper, self.drum_mapper, self.guitar_mapper_list, self.durations_mapper_list, temp=temp, length = length) (guitar_output, bass_output, drum_output) = generated_output guitar_part = create_midipart_with_durations(guitar_output, target_instrument=self.target_instruments[0]) bass_part = create_midipart_with_durations(bass_output, target_instrument=self.target_instruments[1]) #drum_part = create_drum_part_with_durations(drum_output) # TODO fix drum sounds guitar_part.insert(0, self.target_instruments[0]) bass_part.insert(0, self.target_instruments[1]) #drum_part.insert(0, self.target_instruments[2]) full_midi = Score() full_midi.insert(0, guitar_part) full_midi.insert(0, bass_part) #full_midi.insert(0, drum_part) midi_path = f'LSTM_{self.instrument_name}_{j}.mid' full_midi.write('midi', fp=midi_path) midi_to_wav(midi_path, f'static/songs/LSTM_{self.instrument_name}_{j}.wav') self.save_song_to_db(f'LSTM_{self.instrument_name}_{j}.wav') bug = False except ValueError: continue
from music21.chord import Chord from music21.stream import Part, Score from music21.metadata import Metadata from music21.duration import Duration from music21.layout import StaffGroup 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
def predict(self, data, count, temp, length=500): songs = list(set([i.song for i in data])) bug = True while bug: try: condition = True while condition: try: random_song = random.choice(songs) slice_by_instrument = dict( zip(self.target_instruments_str, [[] for i in self.target_instruments_str])) for j in self.target_instruments_str: for i in data: if i.song == random_song and i.instrument == j: slice_by_instrument[j].append(i) slice_by_instrument_without_rests = dict( zip(self.target_instruments_str, [[] for i in self.target_instruments_str])) for i in slice_by_instrument.keys(): for song in slice_by_instrument[i]: if not isinstance(song.chords[0], note.Rest): slice_by_instrument_without_rests[ i].append(song) if len(slice_by_instrument_without_rests[i]) != 0: slice_by_instrument[i] = random.choice( slice_by_instrument_without_rests[i]) else: slice_by_instrument[i] = random.choice( slice_by_instrument[i]) condition = False except IndexError: continue guitar_chords = slice_by_instrument['Electric Guitar'].chords guitar_durations = slice_by_instrument[ 'Electric Guitar'].durations bass_chords = slice_by_instrument['Electric Bass'].chords bass_durations = slice_by_instrument['Electric Bass'].durations combined_guitar = combine_chords_with_durations( guitar_chords, guitar_durations) combined_bass = combine_chords_with_durations( bass_chords, bass_durations) starting_slice_notes = (np.asarray( encode_using_mapper(combined_guitar, self.guitar_mapper)))[:20] starting_slice_bass = (np.asarray( encode_using_mapper(combined_bass, self.bass_mapper)))[:20] songs_in_db_cnt = len(get_songs_by_author(self.db_name)) to_generate = count for j in range(songs_in_db_cnt, songs_in_db_cnt + to_generate): generated_guitar = generate_notes( self.guitar_model, starting_slice_notes, self.guitar_mapper, mapperlist=self.guitar_mapper_list, temp=temp, length=length, normalize=False, random_start=False) generated_bass = generate_notes( self.bass_model, starting_slice_bass, self.bass_mapper, mapperlist=self.bass_mapper_list, temp=temp, length=length, normalize=False, random_start=False) guitar_part = create_midipart_with_durations( generated_guitar, target_instrument=self.target_instruments[0]) bass_part = create_midipart_with_durations( generated_bass, target_instrument=self.target_instruments[1]) guitar_part.insert(0, self.target_instruments[0]) bass_part.insert(0, self.target_instruments[1]) full_midi = Score() full_midi.insert(0, guitar_part) full_midi.insert(0, bass_part) midi_path = f'Transformer_{self.instrument_name}_{j}.mid' full_midi.write('midi', fp=midi_path) midi_to_wav( midi_path, f'static/songs/Transformer_{self.instrument_name}_{j}.wav' ) self.save_song_to_db( f'Transformer_{self.instrument_name}_{j}.wav') bug = False except: continue