def main(): fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa") solution = [52,52,53,55,55,53,52,50,48,48,50,52,52,50,50] #testSol = [1,3,53,55,55,53,52,50,48,48,50,52,52,50,50] population = createInitialPopulation(250, len(solution)) #t = Track() #for note in findMostFit(population,solution): # t + note #fluidsynth.play_Track(t,1) generation = 1 highestFitness = calcFitness(findMostFit(population, solution), solution) print("Generation: 1") print("Initial Highest Fitness: " + str(highestFitness)) #print(calcFitness(testSol,solution)) while highestFitness < 1: population = createNewPopulation(population, solution, .01) generation = generation + 1 highestFitness = calcFitness(findMostFit(population, solution), solution) print("Generation: " + str(generation)) print("Highest Fitness level: " + str(highestFitness)) if generation % 10 == 0: print("hi") t = Track() for noteInt in findMostFit(population,solution): newNote = Note() newNote.from_int(noteInt) t + newNote fluidsynth.play_Track(t,1) #time.sleep(10) t = Track() for note in findMostFit(population,solution): t + note fluidsynth.play_Track(t,1)
async def on_start(self): self.agent.set("current_bar_no", 0) # inicializa "current_bar_no" en 0 # self.agent.set("tempo", 120) # self.agent.set("key", "C") self.agent.set("melody_track", Track()) self.agent.set("accompaniment_track", Track()) self.agent.set("current_melody_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE)) self.agent.set("current_accompaniment_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE))
def play(self, melody, chords, bpm, scores, bars, key, mode, modeToPass, tra, file, out_dir): t2 = Track() sh = progressions.to_chords(chords, key) for i in range(0, len(sh)): b = Bar(None, (4, 4)) if len(chords[i][0]) > 5: b.place_notes(None, 1) else: b.place_notes(NoteContainer(sh[i]), 1) t2 + b fluidsynth.pan(1, 25) fluidsynth.pan(2, 120) fluidsynth.main_volume(2, 50) fluidsynth.play_Tracks([melody, t2], [1, 2], bpm) # sleep(500000) button = Button(text='Clique para rearmonizar!', command=lambda: self.checkReharmonize( chords, scores, bars, key, mode, modeToPass, tra, bpm, file, out_dir), bg='brown', fg='white', font=('helvetica', 9, 'bold')) self.canvas1.create_window(200, 250, window=button)
def init_random_track(key, is_subject=True): notes = keys.get_notes(key) bar = Bar(key=key) while bar.current_beat < 1: # Randomize pitch and duration of each note. duration = 2**random.randint(1, 3) pitch = notes[random.randint(0, 6)] # If it is intened to be a subject, set the first note to the root. if bar.current_beat == 0 and is_subject == True: pitch = notes[0] # If the randomized duration doesn't fit in the bar, make it fit if 1 / duration > 1 - bar.current_beat: duration = 1 / (1 - bar.current_beat) # Place the new note in the bar bar.place_notes(pitch, duration) # Create a track to contain the randomized bar track = Track() track + bar # Return the track return track
def NewTrack(beats, count, withChromatics, with16): """ NewTrack(liczba_uderzeń_w_takcie, liczba_taktów, czy_z_chromatyką, czy_z_16) zwraca krotkę z trackiem i liczbą nut """ track = Track(Instrument()) rhythms = [] noOfNotes = 0 melodyCount = 0 for ii in range(count): rhythms.append(newBarRhythm(beats, with16)) noOfNotes += len(rhythms[ii]) if withChromatics: melody = newMelody(noOfNotes) else: melody = newMelodyWithoutChromatics(noOfNotes) for rhythm in rhythms: b = Bar("C", (beats, 4)) for note in rhythm: k = random.random() if k > pOfRests: b.place_notes(melody[melodyCount], 4 / note) else: b.place_notes(None, 4 / note) melodyCount += 1 track + b return (track, melodyCount)
def track_creator(instrument_name, channel): instrument = MidiInstrument() track = Track(instrument, channel=channel) instrument.name = instrument_name track.instrument.instrument_nr = MidiInstrument.names.index( instrument_name) return track
def shift(track, pause_duration): key = track[0].key shifted_track = Track() bar = Bar(key=key) bar.place_rest(pause_duration) input_note_containers = track.get_notes() for note in input_note_containers: placed = bar.place_notes(note[-1], note[1]) if not placed: beat_left = 1.0 - bar.current_beat beats_part_1 = beat_left beats_part_2 = 1 / note[1] - beats_part_1 if beats_part_1 != 0: duration_part_1 = 1 / beats_part_1 bar.place_notes(note[-1], duration_part_1) shifted_track.add_bar(copy.deepcopy(bar)) bar = Bar(key=key) duration_part_2 = 1 / beats_part_2 bar.place_notes(note[-1], duration_part_2) shifted_track.add_bar(copy.deepcopy(bar)) return shifted_track
def load_from_song(self, song): ''' Fills a mingus-composition object with the data of a Song object ''' if 'bar_length' in song.info: try: self.bar_length = song.info['bar_length'] except: print "You need to specify length of a Bar first before you can do this" for line in song.lines: track = Track() bar = Bar() for segment in line.segments: if segment.type == 'pause': int_val = None elif segment.type == 'note': int_val = segment.pitch n = Note().from_int(int_val + 48) note_length = float(self.bar_length) / segment.duration if not bar.place_notes(n, note_length): track.add_bar(bar) bar = Bar() bar.place_notes(n, note_length) track.add_bar(bar) self.composition.add_track(track) self.path = song.path self.song_name = song.reader.file_name[:-4]
def __init__(self): self.instrument = "Electric Piano 1" self.tempo = 120.0 self.notes = Track() self.length = 16 self.key = "C" self.raw_song = [] self.weights = None
def vector_to_midi(arr, filename="nice.midi"): track = Track() for note_arr in arr: note_num = int(np.argmax(note_arr)) note = Note() note.from_int(note_num - 3) track.add_notes(note) write_Track(filename, track) print("Done!")
def playTrack(arr): fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa") SF2 = '/usr/share/sounds/sf2/FluidR3_GM.sf2' if not fluidsynth.init(SF2): print "Couldn't load soundfont", SF2 sys.exit(1) t = Track() for note in arr: t + note fluidsynth.play_Track(t,1)
def sheets_from_peaks(peaks): """Generate and open the sheet music pdf that represents the notes contained in peaks.""" bass_range = Instrument() bass_range.set_range(['A-0', 'C-4']) bass_track = Track(bass_range) treble_range = Instrument() treble_range.set_range(['C-4', 'C-8']) treble_track = Track(treble_range) treble_track.add_bar(Bar()) bass_track.add_bar(Bar()) for time_slice in peaks: bass_chord, treble_chord = [], [] for note_index, note_value in enumerate(time_slice): if note_value: # add 9 to note_index to start at A-0 note = Note().from_int(note_index + 9) if bass_range.note_in_range(note): bass_chord.append(note) elif treble_range.note_in_range(note): treble_chord.append(note) if bass_chord == treble_chord == []: continue for chord, track in ((bass_chord, bass_track), (treble_chord, treble_track)): if track.bars[-1].is_full(): track.add_bar(Bar()) if chord: print chord track.bars[-1] + chord print track else: track.bars[-1].place_rest(4) print bass_track print treble_track merge_rests(treble_track, bass_track) save_and_print(treble_track, bass_track)
def input_list(list_of_note_tuples): #track to return track = Track() #For every tuple in input for (name, duration) in list_of_note_tuples: #If we can't add note (duration is too long) if not (track.add_notes(name, duration)): #Calculate new duration to fit bar and add note space_left = track[-1].space_left() track.add_notes(name, int(1.0 / space_left)) return track
def __init__(self): """ function to initialize PianoPlayer class """ self.track = Track(Piano()) self.notes = [] #initialize keys for i in range(21, 109): self.notes.append(i) self.matrix = {} for n in self.notes: i = int(n) self.matrix[i] = [0] * 10
def fib_seq(offset=0): track = Track(instrument=Piano()) stop_at = 60 i = 1 f = 1 while f < stop_at: f = fib(i) + offset ni = f % 12 octave = (f / 12) + 1 note = notes.int_to_note(ni) track.add_notes('%s-%d'%(note, octave), 4) i += 1 return track
def get_track(self, dict): """ parse track from matrix representation :param dict: mapping of beats to notes that occurred on that particular beat :param length: :return: """ track = Track() for key in sorted(dict.iterkeys()): notes = dict[key] mingus = [] for chord in notes: mingus.append(chord[0]) track.add_notes(mingus) return track
def createMingusComposition(intermed, timesig, bIsTreble, bSharps): comp = Composition() comp.set_title('Trilled Results') comp.set_author('Author') if bIsTreble: ins = TrebleInstrument('') else: ins = BassInstrument('') track = Track(ins) track.name = 'Part 1' comp.add_track(track) assert len(timesig) == 2 and isinstance(timesig[0], int) and isinstance( timesig[1], int) firstbar = Bar(meter=timesig) track.add_bar(firstbar) mapDurs = { int(intermed.baseDivisions * 4): 1.0, #whole note, int(intermed.baseDivisions * 2): 2.0, #half note int(intermed.baseDivisions * 1): 4.0, #qtr note, and so on int(intermed.baseDivisions * 0.5): 8.0, int(intermed.baseDivisions * 0.25): 16.0, int(intermed.baseDivisions * 0.125): 32.0, int(intermed.baseDivisions * 0.0625): 64.0, } for note in intermed.noteList: if note.pitch == 0 or note.pitch == (0, ): # a rest thepitches = tuple() else: # a note thepitches = [] for pitch in note.pitch: pname, poctave = music_util.noteToName(pitch, bSharps) thepitches.append(pname + '-' + str(poctave)) dur = note.end - note.start if dur not in mapDurs: raise NotesinterpretException('Unknown duration:' + str(dur)) notecontainer = NoteContainer(thepitches) notecontainer.tied = note.isTied bFit = track.add_notes(notecontainer, mapDurs[dur]) assert bFit #note that, naturally, will enforce having correct measure lines, since going across barline throughs exception return comp
def write_mingus(self, outfile): notes = list(self.timeseries['Notes']) t = Track() for n in range(len(notes)): if n % 4 == 0: b = Bar(self.key, (4, 4)) if notes[n] != 'Z': b + notes[n] else: b + None if (n + 1) % 4 == 0: t + b self.composition + t self.track = t lily_composition = LilyPond.from_Composition(self.composition) print lily_composition LilyPond.to_pdf(lily_composition, outfile)
class Song: instrument = "Electric Piano 1" #instrument tempo = 120.0 #tempo in beats per minute notes = Track() #Actual sequence of Notes (defined above) weights = None length = 16 #number of bars in the song key = "C" #key of the song raw_song = [] #the song as a simple list of note/duration pairs def __init__(self): self.instrument = "Electric Piano 1" self.tempo = 120.0 self.notes = Track() self.length = 16 self.key = "C" self.raw_song = [] self.weights = None
def reverse(track, key='C'): # Copy value of reference to aviod problems with overwriting input_track = copy.deepcopy(track) #empty track to write to later reversed_track = Track() b = Bar(key) reversed_track.add_bar(b) #create a reversed list of notes from input track input_notes = input_track.get_notes() reversed_notes = reversed(list(input_notes)) #Add notes to reversed_track for note in reversed_notes: reversed_track.add_notes(note[-1], duration=note[1]) # Return reversed track return reversed_track
def notes_durations_to_track(_notes, durations=None): ''' params: - _notes: list of list of Notes [['G','B','D','F'], ['C','E','G','B']] - durations: Durations should be a list of integers e.g. [2,2,1] will give | chord 1 chord 2 | chord 3 | TO-DO: - mingus durations are limited to =< 1 bar; we want to be able to parse a duration of '0.5' (because in mingus '4'=crotchet i.e. num subdivs) to refer to 2 bars (just use 1/d) ''' if durations is None: durations = [1] * len(_notes) t = Track() for i, _note in enumerate(_notes): b = Bar() b.place_notes(_note, durations[i]) t.add_bar(b) return t
def change_speed(track, factor, key, up=True): changed_track = Track() #if factor is 0 we return an empty track if (factor != 0.0): input_track = copy.deepcopy(track) input_notes = input_track.get_notes() b = Bar(key=key) changed_track.add_bar(b) #if we want to speed up (notespeed *= factor) if up: for note in input_notes: changed_track.add_notes(note[-1], int(note[1] * factor)) #if we want to slow down (notespeed *= (1/factor)) else: for note in input_notes: changed_track.add_notes(note[-1], int(note[1] / factor)) return changed_track
def generate_track(g, n, name): root = np.random.randint(0, n) edges = nx.bfs_edges(g.G, root) nodes = [root] + [v for u, v in edges] m = MidiInstrument(4) t = Track() track = [] t.instrument = m nNotes = 0 print("##### Creating Tracks") for x in nodes: value = t.add_notes(NoteContainer(g.G.nodes[x]["note"]), g.G.nodes[x]["duration"]) t.bars[-1].set_meter((n, 1)) track.append(g.G.nodes[x]["note"]) nNotes = nNotes + 1 print("##### Notes Generated:") print(*t) print("##### Number of notes:") print(nNotes) midi_file_out.write_Track(name + ".mid", t) return t
def main(config_path): pickle_in = open("saved_winners.pickle", "rb") genomes = pickle.load(pickle_in) pickle_in.close() config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path) for x, genome in enumerate(genomes): trainer.eval_fitness([(1, genome)], config) fitness = genome.fitness float_name = fitness * 1000 int_name = int(float_name) name = str(int_name) os.mkdir(name) for i in range(15): song = trainer.generate_song(x + 1) track = Track() for bar in song: track.add_bar(bar) xml = musicxml.from_Track(track) path = name + "\\" + str(i) + ".musicxml" xml_file = open(path, "w") xml_file.write( '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 2.0 Partwise//EN"\n "http://www.musicxml.org/dtds/partwise.dtd">\n' + xml)
def setup_tracks(midi_file_out=None): from tracks import melodies, cantus_firmus, key, meter, species, author # Create a composition, and add the vocal tracks to it. composition = Composition() composition.set_title('Counterpoint Exercise', '') composition.set_author(author, '') # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py tracks = {} for voice in [Soprano, Alto, Tenor, Bass]: if len(melodies[voice.name]): tracks[voice.name] = Track(instrument=voice()) tracks[voice.name].add_bar(Bar(key=key, meter=meter)) tracks[voice.name].name = voice.name for note in melodies[voice.name]: tracks[voice.name].add_notes(*note) composition.add_track(tracks[voice.name]) if midi_file_out is not None: # Save the midi file! write_Composition(midi_file_out, composition, verbose=True) return composition, [], species
def export(melody_track, chords, key, time_sig, bpm, file): i = Instrument() i.instrument_nr = 1 t2 = Track() for i in range(0, len(chords)): b = Bar(key, time_sig) if len(chords[i][0]) > 5: b.place_notes(None, 1) else: b.place_notes(NoteContainer(chords[i]), 1) t2 + b c = Composition() c.add_track(melody_track) c.add_track(t2) out_dir = 'out' if not os.path.exists(out_dir): os.makedirs(out_dir) mid = file.split('/')[-1] if os.path.exists(out_dir + '/' + mid): os.remove(out_dir + '/' + mid) MidiFileOut.write_Composition(out_dir + '/' + mid, c, bpm) file = out_dir + '/' + mid sys.argv.append('') sys.argv.append('') sys.argv[1] = "--midi-file=" + file sys.argv[2] = "--out-dir=" + out_dir midi.main() if os.path.exists(file): os.remove(file)
c.augment() #升半音 c.diminish() #降半音 c.remove_redundant_accidentals() #清理多余升降号(只能成对清理,烂) #谱容器 from mingus.containers import NoteContainer #创建谱容器对象(继承列表,完全可以按列表操作,不用看下面的) n = NoteContainer(['A-3', 'C-5', 'B-4']) n.add_note('F-1') # 0位加音 n.remove_note('B', 4) #删音 n.empty() #清空 #乐器音色 from mingus.containers.instrument import Instrument, Piano, Guitar #创建乐器对象 i = Instrument() i.range #乐器音域 i.set_range((Note('C-2'), Note('E-4'))) #设定音域 i.note_in_range('F-4') #判断音是否在乐器音域内 #音轨 from mingus.containers import Track t = Track(i) #乐器放入音轨容器 #MIDI音乐播放(安装困难) #from mingus.midi import fluidsynth #fluidsynth.init("soundfont.SF2") #fluidsynth.play_Note( Note('C-5') ) from mingus.midi import MidiFileOut MidiFileOut.write_NoteContainer('test.mid', n)
cymbalpercussion = [] tompercussion = [] major_chords = [ simple_chordI, simple_chordIV, simple_chordV, simple_chordIi, complex_chordI, complex_chordIV, complex_chordV, complex_chordIi ] minor_chords = [ simple_chordII, simple_chordIII, simple_chordVI, simple_chordV7, complex_chordII, complex_chordIII, complex_chordVI, complex_chordV7 ] left_hand_music = [] right_hand_list = [] right_hand_music = [] downbeatbar = Bar() righthandbar = Bar() synthtrack1 = Track() synthtrack1.instrument = synth electricguitartrack1 = Track() electricguitartrack1.instrument = electricguitar brasstrack1 = Track() brasstrack1.instrument = brass bassetrack1 = Track() bassetrack1.instrument = basse strintrack1 = Track() strintrack1.instrument = string guitartrack1 = Track() guitartrack1.instrument = guitar frhorntrack1 = Track() frhorntrack1.instrument = frhorn righthandtrack1 = Track() righthandtrack1.instrument = brightpiano
def Track_from_list(listt=[[[0.0, 8.0, None], [0.125, 16.0, ['C-6']]]]): t = Track() for bars in listt: t.add_bar(bars) return t
def temporal_realign_track_bars(track, pickup=None, give_notes=False, give_durations=False, debug=False): '''Realign notes within bar lines (e.g. splitting rest events which cross barlines after reading in from midi) Warning: do not begin a bar with an acciacatura as current_pos will get out of sync (acciacatura implies rests and anticipation which gets confusing for timing) (at least in the case where the previous bar ends with a rest, not tested otherwise)''' notes = [notev[2] for notev in track.get_notes()] durations = [notev[1] for notev in track.get_notes()] # output will get out of alignment if we start mid-bar, let's workaround by padding with rests at start if pickup == 0: # input sanitising pickup = None if pickup is not None: notes = [[]] + notes durations = [1/pickup] + durations notes2 = [] durations2 = [] current_pos = 0 # maybe this should be set negative in the case of a pickup bar / upbeat ? e.g. determined by split pos for i, duration in enumerate(durations): # if a duration < 1.0 then we have a conjoined bar # e.g. a rest of duration 0.88888 is the same as 1.0 + 0.125 (i.e. whole plus quarter rest) # because 1/0.8888 = 1.125 if duration < 1.0: ones = int(1//duration) # // gives integer part of div remainder = 1/duration - ones # check if we are at the end/start of a new bar if round(current_pos*2**10)/2**10 == current_pos//1 or round(current_pos*2**10)/2**10 == current_pos//1 + 1: if debug: print('splitting rest',i) new_durations = ones*[1.0] + [1/remainder] else: # if we are part way through a bar then the rem comes first new_durations = [1/remainder] + ones*[1.0] notes2 += (ones+1)*[notes[i]] durations2 += new_durations current_pos += 1/durations[i] else: if debug: print(i, 'current_pos',current_pos, round(current_pos*2**10)/2**10, 1/durations[i], current_pos + 1/durations[i]) notes2.append(notes[i]) durations2.append(durations[i]) current_pos += 1/durations[i] t = Track() if debug: t2 = Track() print(len(durations2), durations2) print(len(notes2), notes) for i, _ in enumerate(durations2): if debug: if not t2.add_notes(notes2[i], durations2[i]): print('') print(f'failed to add {notes2[i]}, {durations2[i]} to on index {i}') print(i, t2.bars[-3:]) print('') t.add_notes(notes2[i], durations2[i]) # outputs if give_notes and give_durations: return t, notes2, durations2 elif give_notes: return t, notes2 elif give_durations: return t, durations2 else: return t