def __init__(self, inFilename, outFilename): MIDIFile.__init__(self, numTracks=MIDIView.voices, deinterleave=False) self.reset(inFilename, outFilename) self.setMono() self.chunkSize = int(self.rate * Isolator.resolution) self.indexes = range(self.chunkSize, len(self.mono) + 1, self.chunkSize)
def save_genome_to_midi(filename: str, genome: Genome, num_bars: int, num_notes: int, num_steps: int, pauses: bool, key: str, scale: str, root: int, bpm: int): melody = genome_to_melody(genome, num_bars, num_notes, num_steps, pauses, key, scale, root) if len(melody["notes"][0]) != len(melody["beat"]) or len( melody["notes"][0]) != len(melody["velocity"]): raise ValueError mf = MIDIFile(1) track = 0 channel = 0 time = 0.0 mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, bpm) for i, vel in enumerate(melody["velocity"]): if vel > 0: for step in melody["notes"]: mf.addNote(track, channel, step[i], time, melody["beat"][i], vel) time += melody["beat"][i] os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "wb") as f: mf.writeFile(f)
def getNoteGroupCluster(vsqxPath): # Encode info into vector df = None params = None noteClusterList = [] path = PurePath(vsqxPath) vsqx = xml.dom.minidom.parse(str(path)) TEMPO = int( vsqx.getElementsByTagName('tempo') [0].childNodes[1].firstChild.data[:-2]) mf = MIDIFile(len(vsqx.getElementsByTagName('vsTrack')), removeDuplicates=False) time = 0 for trackNo, track in enumerate(vsqx.getElementsByTagName('vsTrack')): mf.addTrackName(trackNo, time, "Track {}".format(str(trackNo))) #print('track: ',trackNo) #i = 0 timeOffset = 0 prevTime = 0 durTime = 0 for noteCount, note in enumerate(track.getElementsByTagName('note')): #print(noteCount) params, noteClusterList = createNoteCluster( note, params, noteClusterList, track) #mf.addNote(trackNo, 0, getNoteData(note, 'n'), currTime / 480, getNoteData(note, 'dur') / 480, 64) #mf.addTempo(trackNo, time, TEMPO) return (params, noteClusterList)
def render_midi(spec_path, o_path="", cycle_instr=False): with open(spec_path) as data: spec = json.load(data) tempo = spec['bpm'] tracks = spec['tracks'] for idx, t in enumerate(tracks): nts = [(x + 1) + t['note_floor'] for x in t['notes']] midi_track = MIDIFile(1) note_dur = 4 / t['note_length'] track_notes = list(nts) track = 0 channel = idx time = note_dur duration = note_dur volume = 127 if 'midi_volume' not in t.keys() else t['midi_volume'] instrument = 1 if 'midi_instrument' not in t.keys() else t['midi_instrument'] midi_track.addTempo(track, time, tempo) for i, pitch in enumerate(track_notes): if cycle_instr: instrument = int(abs(math.sin((1/(len(track_notes))) * i)) * 127) midi_track.addProgramChange(track, channel, time * i, instrument) midi_track.addNote(track, channel, pitch, time * i, duration, volume) with open(o_path + '_-_Track 0' + str(idx+1)+".mid", "wb") as output_file: midi_track.writeFile(output_file)
def write_midi(melody, id): old_pitch_list = melody.strip().split(' ') pitch_list = [] for i in range(len(old_pitch_list)): if i % 2 == 0: pitch_list.append(old_pitch_list[i]) # return pitch_list # create your MIDI object mf = MIDIFile(1) # only 1 track track = 0 # the only track time = 0 # start at the beginning mf.addTrackName(track, time, "Sample Track" + str(id)) mf.addTempo(track, time, 120) # add some notes channel = 0 volume = 100 for note in pitch_list: pitch = pitch_dict[note] duration = 1 # 1 beat long mf.addNote(track, channel, pitch, time, duration, volume) time += 2 # write it to disk with open("/home/ubuntu/team15/midi/record/" + str(id) + '.txt', 'w') as outtxt: for pitch in pitch_list: outtxt.write("%s\n" % pitch) midi_name = str(id) + ".mid" with open("/home/ubuntu/team15/midi/" + midi_name, 'wb') as outf: mf.writeFile(outf) return midi_name
def save(Clip, filename='music.mid', tempo=140): track = 0 time = 0 channel = 0 duration = 0 MIDI = MIDIFile(1) MIDI.addTempo(track, time, tempo) durations_index = 0 for i, pitch in enumerate(Clip.midi_notes): if type(pitch) is int: if pitch != -1: MIDI.addNote(track, channel, pitch, time + i, Clip.durations[durations_index], Clip.accent_map[i]) else: for pitch2 in Clip.midi_notes[i]: MIDI.addNote(track, channel, pitch2, time + i, Clip.durations[durations_index], Clip.accent_map[i]) if pitch != -1: durations_index += 1 with open(filename, "wb") as output_file: MIDI.writeFile(output_file)
def write_midi(self,name): """writes midi file for the piece""" time = 0 MyMIDI = MIDIFile(1) MyMIDI.addTempo(track, time, tempo) for idea in self.ideas: for note in idea.melody: for pitch in note.pitch: MyMIDI.addNote(track, channel, pitch, time, note.duration, volume) time += note.duration # adding bass time = 0 for idea in self.ideas: for note in idea.bass: for pitch in note.pitch: MyMIDI.addNote(track, channel+1, pitch, time, note.duration, volume) time += note.duration with open(f"{name}.mid", "wb") as output_file: MyMIDI.writeFile(output_file) print(f'Done! Midi file saved as "{name}.mid"')
def createMIDI(tempo): midiFile = MIDIFile(1) midiFile.addTempo(0, 0, tempo) return midiFile
def runMido(self): mid = mido.MidiFile('./scripts/Magenta/SecondOutput/SecondOutput.mid') onOff = [] notes = [] time = [] trackTime = 0 program = 0 tempo = 60 MyMIDI = MIDIFile(1) MyMIDI.addProgramChange(0, 0, 0, self.program) MyMIDI.addTempo(0, 0, self.tempo) print("start") for msg in mid.play(): onOff.append(msg.type) time.append(msg.time) test = msg.bytes() notes.append(test[1]) print("finished") for i in range(0, len(notes)): MyMIDI.addNote(0, 0, notes[i], trackTime + time[i], 1, 100) trackTime += time[i] with open("static/audio/" + self.name + ".mid", "wb") as output_file: MyMIDI.writeFile(output_file)
def writeSong(self, ascii_text): self.reset() MyMIDI = MIDIFile(16) MyMIDI.addTempo(0, 0, 120) MyMIDI.addProgramChange(4, 4, 0, 37) MyMIDI.addProgramChange(5, 5, 0, 38) ascii_text = self.getCountIn() + ascii_text trackCt = 0 for lines in ascii_text.split("\n"): trackCt = 0 print str(len(lines.split(","))) + ":" + lines + ":Track=" + str( trackCt) + ":Time=" + str(self.time) for note in lines.split(","): if note != "": if (trackCt < 4): channel = 9 else: channel = trackCt print "adding " + str(trackCt) + " " + str( channel) + " " + str(note) + " " + str( self.time) + " 1 127" MyMIDI.addNote(trackCt, channel, int(note) - 1, self.time, 0.5, 127) trackCt = trackCt + 1 if len(lines.split(",")) == 6: self.time = self.time + 0.25 with open("myfilename.mid", "wb") as output_file: MyMIDI.writeFile(output_file)
def convert_to_MIDI(self, instruments=["Piano"], start_times=[4], tempos=[80], tracks=1, channel=0, volume=100): if not self.verify_track(tracks): return #Adjusts instrument, start_times, and tempos to match with number of specified tracks instr = self.set_instruments(instruments, tracks) self.set_start_times(start_times, tracks) self.set_tempos(tempos, tracks) MIDI_File = MIDIFile(tracks, adjust_origin=False) print len(self.SOLset) #for every track of the Midi File for t in range(tracks): print('T,instruments,tempos: %s, %s, %s', (t, instr, tempos)) MIDI_File.addTempo(t, 0, tempos[t]) #Adds tempo t MIDI_File.addProgramChange(t, 0, 0, instr[t]) #sets instrument for tempo t prevAccidental = -1 #if the previous sheet object was a sharp or flat currOctave = 1 time = start_times[ t] #Current time placement of a not in the given track #For every object in a single sheet object list for ob in self.SOLset[t]: #print(ob.clef,ob.duration,ob.run) #If object is an accidental, set variable and finish current iteration if ob.accidental != -1: prevAccidental = ob.accidental continue #If the object is a clef, set currOctave and finish current iteration if ob.clef != -1: currOctave = ob.clef continue #Calculate note id and pitch note_id = self.note_id(ob.run, currOctave) pitch = self.note_pitch(note_id, prevAccidental) #Reset accidental to base value prevAccidental = -1 if ob.duration > 0 and ob.rest != 1: #If the object has a note duration, add it as a note MIDI_File.addNote(t, t, pitch, time + ob.duration, ob.duration, volume) time = time + ob.duration elif ob.rest > 0: #If the object has a rest duration, add it as a rest MIDI_File.addNote(t, t, 0, time + ob.rest, ob.rest, 0) time = time + ob.rest self.MIDI = MIDI_File
def save_melody_to_midi(melody, filename: str): if len(melody["notes"][0]) != len(melody["beat"]) or len( melody["notes"][0]) != len(melody["velocity"]): raise ValueError mf = MIDIFile(1) track = 0 channel = 0 time = 0.0 mf.addTrackName(track, time, "Sample Track") mf.addTempo(track, time, bpm) for i, vel in enumerate(melody["velocity"]): if vel > 0: for step in melody["notes"]: mf.addNote(track, channel, step[i], time, melody["beat"][i], vel) time += melody["beat"][i] os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "wb") as f: mf.writeFile(f)
def __init__(self, tempo=120): self.tempo = tempo # In BPM self.track = 0 self.time = 0 self.channel = 0 self.MyMIDI = MIDIFile(1) # One track, defaults to format 1 self.MyMIDI.addTempo(self.track, self.time, self.tempo)
def to_midi_wav(melody): # convert to midi filename = melody['raw_filename'] k = melody['duration'] * melody['bpm'] / (np.array(melody['lengths']).sum() * 60) time = 0 track = 0 channel = 0 volume = 100 my_midi = MIDIFile(1) my_midi.addTempo(track, time, melody['bpm']) my_midi.addProgramChange(track, channel, time, 0) for i, pitch in enumerate(melody['midi']): length = k * melody['lengths'][i] if pitch != 'P' and 0 <= pitch <= 255 and length >= 1/16: my_midi.addNote(track, channel, round(pitch), time, length, volume) time = time + k * melody['lengths'][i] midi_filename = 'tmp/' + filename.split('.')[0] + '.mid' with open(midi_filename, "wb") as output_file: my_midi.writeFile(output_file) # convert back to wav filename_processed = 'tmp/'+ filename.split('.')[0] + '_processed' + '.wav' fs = FluidSynth('static/Drama Piano.sf2') fs.midi_to_audio(midi_filename, filename_processed)
def play_midi_file( midi: MIDIFile, tmp_dir="temp", soundfont='mung2midi/UprightPianoKW-small-SF2-20190703/UprightPianoKW-small-20190703.sf2', cleanup=False): """Plays (or attempts to play) the given MIDIFile object. :param midi: A ``midiutils.MidiFile.MIDIFile`` object containing the data that you wish to play. :param tmp_dir: A writeable directory where the MIDI will be exported into a temporary file. :param soundfont: A *.sf2 soundfont for FluidSynth to load. """ tmp_midi_path = os.path.join(tmp_dir, 'play_' + str(uuid.uuid4())[:8] + '.mid') with open(tmp_midi_path, 'wb') as hdl: midi.writeFile(hdl) if not os.path.isfile(tmp_midi_path): logging.warning('Could not write MIDI data to temp file {0}!'.format( tmp_midi_path)) return play_midi_file_from_disk(tmp_midi_path, soundfont) # Here's hoping it's a blocking call. Otherwise, just leave the MIDI; # MUSCIMarker cleans its tmp dir whenever it exits. if cleanup: os.unlink(tmp_midi_path)
def __init__(self): self.mid = MIDIFile(1) # Where prospective midi files are stored self.track = 0 self.channel = 0 self.time = 0 self.tempo = 140 # in BPM self.volume = 100
def generate_measure(num_tracks: int, drum_groups: List[DrumGroup], drum_hits: pd.DataFrame) -> MIDIFile: """ Core function that generates a measure of drum hits. Places contents in what is effectively a temporary container """ midi_measure = MIDIFile(numTracks=num_tracks) for row in drum_hits.itertuples(): time = row.Index for i, drum_group in enumerate(drum_groups): # Slice the drum group out of the set of groups # Offset of 1 to adjust for presence of pandas Index column l_bound = i * len(DrumChance._fields) + 1 drum_chance = DrumChance(*row[l_bound:l_bound + len(DrumChance._fields)]) # Core random check which drives the drum hit if random.random() <= drum_chance.prob_hit: nudge = random.randrange(-1 * drum_group.nudge, drum_group.nudge) * 0.01 # Choose which drum from set of drum groups based on stated probabilities pitch_pos = np.random.choice(np.arange(0, len(drum_group.prob_pitch)), p=drum_group.prob_pitch) midi_measure.addNote(track=drum_group.track - 1, channel=0, pitch=drum_group.midi_pitch_set[pitch_pos], time=max(0, time + nudge), duration=(drum_chance.duration / pulses_beat) - nudge, volume=random.randint(drum_chance.min_vol, drum_chance.max_vol)) return midi_measure
def __init__(self, tempo=120, volume=100): self.tempo = tempo # In BPM self.track = 0 self.time = 0 self.volume = volume # 0-127, as per the MIDI standard self.channel = 0 self.MyMIDI = MIDIFile(1) # One track, defaults to format 1 self.MyMIDI.addTempo(self.track, self.time, self.tempo)
def __init__(self, tempo): self.track = 0 self.channel = 10 # channel (drum standard) self.volume = 100 # volume self.__MyMIDI = MIDIFile( 1 ) # one track, defaults to format 1 (tempo track is created automatically) self.__MyMIDI.addTempo(self.track, 0, tempo) # add tempo (bpm) to file
def createSong(self): self.MyMIDI = MIDIFile(1, removeDuplicates=True, adjust_origin=True) # One track self.MyMIDI.addTempo(self.track, self.time, self.tempo) self.createDictionaries() self.createLists() self.implementSong(self.entryText) self.saveSong()
def __init__(self, tempo): self.track = 0 self.channel = 10 self.volume = 100 # 0-127, as per the MIDI standard self.__MyMIDI = MIDIFile( 1 ) # One track, defaults to format 1 (tempo track is created automatically) self.__MyMIDI.addTempo(self.track, 0, tempo)
def __init__(self, generator): self.midiExportFile = MIDIFile(2) # (track, time, tempo) self.midiExportFile.addTempo(1000, 0, bpm) numerator = generator.beatPerMeasure denominator = int(math.log(generator.beatUnit, 2)) clocksPerTick = int(24 * (4 / generator.beatUnit)) self.midiExportFile.addTimeSignature(1000, 0, numerator, denominator, clocksPerTick)
def compile(self, song_generator): self.generator = MIDIFile(1) for i in song_generator.song: self.generator.addProgramChange(0, song_generator.song[i]["channel"], 0, song_generator.song[i]["program"]) for note in song_generator.song[i]["note_series"]: self.generator.addNote(0, song_generator.song[i]["channel"], note["pitch"], note["time"], note["duration"], note["volume"]) for i in song_generator.events: if i["type"] == "tempo": self.generator.addTempo(0, i["time"], i["value"]) self.write_to_file()
def __init__(self, path='melody.mid', tempo=200): self._path = path self._melody = MIDIFile(1, True, True, True) self._track = 0 self._tempo = tempo self._melody.addTempo(self._track, 0, tempo) self._free_channels = [x for x in range(16, -1, -1) if x != 9] self._current_channel = 0 self._beat_instrument = 0 self._beat_drum = 0
def convert_to_MIDI(self, degrees, track=0, channel=0, time=1, tempo=100, volume=100): MIDI_File = MIDIFile(1) MIDI_File.addTempo(track,time,tempo) degrees = self.calculate_degress(SOL) for time_inc, pitch in enumerate(degrees): MIDI_File.addNote(track, channel, pitch, time + time_inc, duration volume) return MIDI_File
class MIDISetup: def __init__(self, outputFileName): self.outputFileName = outputFileName def __enter__(self): self.midi = MIDIFile( 3) # One track, defaults to format 1 (tempo track is created return self.midi def __exit__(self, type, value, traceback): with open("{}.mid".format(self.outputFileName), "wb") as output_file: self.midi.writeFile(output_file)
def makemidi(img, midi, lo=74, hi=110): if int(lo) > 0: lo = 0 if int(hi) < 127: hi = 127 filename = img if filename.endswith('.png'): a = cv2.imread(filename, cv2.IMREAD_UNCHANGED) trans = a[:, :, 3] == 0 a[trans] = [255, 255, 255, 255] a = cv2.cvtColor(a, cv2.COLOR_BGRA2BGR) else: a = cv2.imread(filename, cv2.IMREAD_UNCHANGED) h, w = a.shape[:2] scale = w / h w = int(127 * scale) dim = (w, 127) res = cv2.resize(a, dim, interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY) (tresh, newimg) = cv2.threshold(gray, 127, 225, cv2.THRESH_BINARY) # cv2.imshow('jjj', newimg) # cv2.waitKey(0) # cv2.destroyAllWindows() color = 0 pixels1 = np.argwhere(newimg == 0) pixels2 = np.argwhere(newimg == 225) if pixels1.shape > pixels2.shape: pixels = pixels2 else: pixels = pixels1 MyMIDI = MIDIFile( 4) # One track, defaults to format 1 (tempo track is created # automatically) MyMIDI.addTempo(0, 0, 180 * scale) MyMIDI.addProgramChange(0, 0, 0, 0) for note, step in pixels: MyMIDI.addNote(0, 0, 127 - note + 1, step, 1, random.randint(int(lo), int(hi))) with open(midi, "wb") as output_file: MyMIDI.writeFile(output_file) exit("write {} successful".format(midi))
def createAnnotation(yPred, frameduration, audiopath, audiofilename, noteMin): track = 0 channel = 0 time = 0 tempo = 60 MyMIDI = MIDIFile(1) MyMIDI.addTempo(track, time, tempo) lengthAudioFrames = len(yPred) times = np.arange(0.00, lengthAudioFrames, frameduration) times = ["%.2f" % (round(t, 2)) for t in times] offset = (preprocessing.getMIDIfromNote(noteMin)) - 1 notesPred = preprocessing.getNotesfromF0Labels(yPred, offset) startTimesList = [] endTimesList = [] notesList = [] for index, note in enumerate(notesPred): if(note == 'None'): continue else: if(note == notesPred[index-1] and note == notesPred[index+1]): continue else: if(note != notesPred[index-1] and note != notesPred[index+1]): startTimesList.append(times[index]) notesList.append(note) endTimesList.append(times[index]) MIDIpitch = preprocessing.getMIDIfromNote(note) MIDItime = float(times[index]) MIDIduration = 0.01 MyMIDI.addNote(track, channel, MIDIpitch, MIDItime, MIDIduration, volume=100) elif(note != notesPred[index-1] and note == notesPred[index+1]): startTimesList.append(times[index]) notesList.append(note) elif(note == notesPred[index-1] and note != notesPred[index+1]): endTimesList.append(times[index]) MIDIpitch = preprocessing.getMIDIfromNote(note) MIDItime = float(startTimesList[-1]) MIDIduration = float(times[index]) - MIDItime + 0.01 MyMIDI.addNote(track, channel, MIDIpitch, MIDItime, MIDIduration, volume=100) startTimes = pd.DataFrame(startTimesList) endTimes = pd.DataFrame(endTimesList) notes = pd.DataFrame(notesList) groundTruthClean = pd.concat([startTimes, endTimes, notes], axis=1) groundTruthClean.columns = ["Start Time (s)", "End Time (s)", "Note"] fileIsol = preprocessing.extractFileName(audiofilename) groundTruthClean.to_csv(audiopath+'/'+fileIsol+'.csv', sep=',') with open(audiopath+'/'+fileIsol+".mid", "wb") as outputFile: MyMIDI.writeFile(outputFile) print("Created groundtruth .csv and MIDI under filename in project filepath")
def write_to_midi(song, filename, *tempo): track = 0 channel = 0 time = 0 # In beats if not tempo: tempo = 160 # In BPM else: tempo = tempo[0] volume = 100 # 0-127, as per the MIDI standard MyMIDI = MIDIFile(1) # One track, defaults to format 1 (tempo track # automatically created) MyMIDI.addTempo(track, time, tempo) for i in range(len(song)): if song[i][0] < 60: volume = 92 elif song[i][0] < 50: volume = 86 elif song[i][0] < 45: volume = 83 else: volume = 100 MyMIDI.addNote(track, channel, song[i][0], song[i][2], Space_Values[song[i][1]], volume) with open(filename + ".mid", "wb") as output_file: MyMIDI.writeFile(output_file)
def generate_melody(length, root): #seed the randome number generator seed() base = int(root) len = int(length) #prepare a major scale array based off the root, C4 is 60 notes = [base+0, base+2, base+4, base+5, base+7, base+9, base+11, base+12] degrees = [] #generate a sequence of the length for i in range(0, len): degrees.append(notes[randint(0,7)]) track = 0 channel = 0 time = 0 #in beats duration = randint(1,4,len) #in beats tempo = 100 #in BPM volume = 100 #0-127, as per the MIDI standard MyMIDI = MIDIFile(1) #one track, defaults to format 1(tempo track created auto) MyMIDI.addTempo(track,time,tempo) current = 0 for i, pitch in enumerate(degrees): MyMIDI.addNote(track, channel, pitch, current, duration[i], volume) current = current + duration[i] with open("generated.mid", "wb") as output_file: MyMIDI.writeFile(output_file)
async def make_midi(self, tempo: int, data: str) -> MIDIFile: midi_file = MIDIFile(1) midi_file.addTrackName(0, 0, 'beep boop') midi_file.addTempo(0, 0, tempo) channel_datas = data.split('|') log.debug(f'creating MIDI out of "{data}"') for channel_index, channel_data in enumerate(channel_datas): await self.add_channel(midi_file, channel_index, channel_data) log.info('successfully created MIDI') return midi_file