def apply_mutation(mutantnotelist, midino, snote=50, time=150, filename='random'): mid = MidiFile(type=0) # type0 can have only one track track = MidiTrack() # note list (kind of) mid.tracks.append(track) # Create mutant music folder if it does not exist if not os.path.exists('mutantmusic'): os.makedirs('mutantmusic') # add the octaves back mutantnotelist2 = [x+snote for x in mutantnotelist] for note in mutantnotelist2[:len(mutantnotelist2)-2]: #print(note) track.append(Message('note_on', note=int(note), velocity = 127, time=time)) track.append(Message('note_off', note=int(note), velocity = 127, time=time)) track.append(Message('note_on', note=mutantnotelist2[len(mutantnotelist2)-1], velocity = 127, time=time)) track.append(Message('note_off', note=mutantnotelist2[len(mutantnotelist2)-1], velocity = 127, time=500)) mid.save('mutantmusic/' + filename + str(midino) + '.mid')
def generate_midi(self, filename, length=100, delay=96): output = MidiFile() byte_list = super().generate_obj_list(length) track = parse_all(byte_list) for message in track: message.time = delay output.tracks.append(self.metamessages) output.tracks.append(track) output.save(filename)
def split_midi_orch(f, c, list_instru): # Read a midi file and return a dictionnary {track_name : pianoroll} mid_in = MidiFile(f) mid_orch = MidiFile() mid_solo = MidiFile() # The two files need to have the same ticks per beat ticks_per_beat = mid_in.ticks_per_beat mid_orch.ticks_per_beat = ticks_per_beat mid_solo.ticks_per_beat = ticks_per_beat # get instrumentation with open(c, 'rb') as csvfile: reader = csv.DictReader(csvfile, delimiter=',') instrumentation = next(reader) # Parse track by track for i, track_in in enumerate(mid_in.tracks): if track_in.name not in instrumentation.keys(): # probably a metadata track, usefull for both files mid_solo.tracks.append(track_in) mid_orch.tracks.append(track_in) elif instrumentation[track_in.name] in list_instru: mid_solo.tracks.append(track_in) else: mid_orch.tracks.append(track_in) # Create the files path_orch = re.sub(ur'\.mid$', ur'_orch.mid', f, flags=re.I|re.U) path_solo = re.sub(ur'\.mid$', ur'_solo.mid', f, flags=re.I|re.U) mid_orch.save(path_orch) mid_solo.save(path_solo) return path_orch, path_solo
def __init__(self, _save_path, songfile, _plyr_ctrls): super(PlayerThread, self).__init__() self.name = 'Player' self.stoprequest = threading.Event() self.plyr_ctrls = _plyr_ctrls self.chan_roles = [0 for i in range(10)] self.plyr_ctrls['songfile'] = songfile self.midifile = MidiFile(_save_path + songfile) # 0 - drum fill self.counter = [0 for i in range(4)] self.wt = WolfTonesSong() self.save_path = _save_path self.load_song(songfile) self.alt_meas = [] #get the portname (system specific) env = socket.gethostname() if(env == 'record_synth'): names = str(mido.get_output_names()) ports = names.split(',') sobj = re.search(r'Synth input port \(\d*:0\)', ports[0], flags=0) portname = sobj.group() if(env == 'colinsullivan.me'): #dummy port for testing on a headless server with no audio portname = 'Midi Through:Midi Through Port-0 14:0' self.outport = mido.open_output(portname, autoreset=True)
def generate_random(snote=50, mlength=12, numofmidi=10, time=150, filename='random', pitchrnd=False): notes = range(snote, snote+mlength) noterange = range(mlength) # pitch range for random pitch value ; pitches = range(-8192,8191) # Create music folder if it does not exist if not os.path.exists('music'): os.makedirs('music') for j in range(numofmidi): mid = MidiFile(type=0) # type0 can have only one track track = MidiTrack() # note list (kind of) mid.tracks.append(track) # the note which the pitch will change for pitchnote = random.choice(noterange) numofpnote = random.choice(noterange) for i in noterange: note = random.choice(notes) pitch = random.choice(pitches) if pitchrnd: if i == pitchnote: # Change the pitch on the note track.append(Message('pitchwheel', pitch=pitch)) if i == (pitchnote+numofpnote): # Change the pitch back to default track.append(Message('pitchwheel')) track.append(Message('note_on', note=note, velocity = 127, time=time)) track.append(Message('note_off', note=note, velocity = 127, time=time)) note = random.choice(notes) track.append(Message('note_on', note=note, velocity = 127, time=time)) track.append(Message('note_off', note=note, velocity = 127, time=500)) mid.save('music/' + filename + str(j) + '.mid')
def time_warp(source_path, dest_path, ratio): # Read a midi file and return a dictionnary {track_name : pianoroll} mid_in = MidiFile(source_path) mid_out = MidiFile() # The two files need to have the same ticks per beat ticks_per_beat = mid_in.ticks_per_beat mid_out.ticks_per_beat = ticks_per_beat # Parse track by track for i, track_in in enumerate(mid_in.tracks): track_out = MidiTrack() mid_out.tracks.append(track_out) for message_in in track_in: time_in = message_in.time time_out = int(round(time_in * ratio)) # For absolutely every message, just mutliply the time by the ratio message_out = message_in.copy(time=time_out) track_out.append(message_out) mid_out.save(dest_path) return
def createMidiFromPianoRoll(piano_roll, lowest_note, directory, mel_test_file, threshold, res_factor=1): ticks_per_beat = int(96/res_factor) mid = MidiFile(type=0, ticks_per_beat=ticks_per_beat) track = MidiTrack() mid.tracks.append(track) mid_files = [] delta_times = [0] for k in range(piano_roll.shape[1]):#initial starting values if piano_roll[0, k] == 1: track.append(Message('note_on', note=k+lowest_note, velocity=100, time=0)) delta_times.append(0) for j in range(piano_roll.shape[0]-1):#all values between first and last one set_note = 0 #Check, if for the current timestep a note has already been changed (set to note_on or note_off) for k in range(piano_roll.shape[1]): if (piano_roll[j+1, k] == 1 and piano_roll[j, k] == 0) or (piano_roll[j+1, k] == 0 and piano_roll[j, k] == 1):#only do something if note_on or note_off are to be set if set_note == 0: time = j+1 - sum(delta_times) delta_times.append(time) else: time = 0 if piano_roll[j+1, k] == 1 and piano_roll[j, k] == 0: set_note += 1 track.append(Message('note_on', note=k+lowest_note, velocity=100, time=time)) if piano_roll[j+1, k] == 0 and piano_roll[j, k] == 1: set_note += 1 track.append(Message('note_off', note=k+lowest_note, velocity=64, time=time)) mid.save('%s%s_th%s.mid' %(directory, mel_test_file, threshold)) mid_files.append('%s.mid' %(mel_test_file)) return
def new_song(self): # save path here should be /songs/temp path = self.save_path fn = self.wt.get_by_genre(save_path=path) songfile = fn self.midifile = MidiFile(songfile) self.plyr_ctrls['songfile'] = songfile #logging.debug(str(self.midifile.tracks)) # length of a quarter note self.ticks_per_beat = self.midifile.ticks_per_beat #self.chan_roles = [0 for i in range(10)] for trk in self.midifile.tracks: s = trk.name.split(':') chan = s[0] role = s[1] #logging.debug('read ' + chan + ' as ' + role) self.chan_roles[int(chan)] = role ld_role = len(re.match('ld', role)) > 0 if(ld_role): logging.debug('making riff') self.make_riff(trk) logging.debug('Channel ' + str(chan) + ' is ' + role)
def load_song(self, filename): self.stop() tmp = filename.split('.') # if you forget or are too lazy to type the filetype extenstion if(len(tmp) > 1 and tmp[-1] != 'mid'): filename += '.mid' songfile = self.save_path + filename self.wt.load_file(songfile) self.midifile = MidiFile(songfile) self.plyr_ctrls['songfile'] = filename #logging.debug(str(self.midifile.tracks)) # length of a quarter note self.ticks_per_beat = self.midifile.ticks_per_beat #self.chan_roles = [0 for i in range(10)] for trk in self.midifile.tracks: s = trk.name.split(':') chan = s[0] role = s[1] #logging.debug('read ' + chan + ' as ' + role) self.chan_roles[int(chan)] = role if(role[-3:] == '_ld'): logging.debug('making riff') self.make_riff(trk) logging.debug('Channel ' + str(chan) + ' is ' + role)
from mido import MidiFile import os filename = 'e-competition_out/2002/chan01.mid' mid = MidiFile(filename) directories = ['e-competition_out/2002/', 'e-competition_out/2004/', 'e-competition_out/2006/', 'e-competition_out/2008/', 'e-competition_out/2009/', 'e-competition_out/2011/'] #directories = ['e-competition_out/2011/'] notesOnPerDirectory = [0] * len(directories) totalFiles = 0 for directoryIndex in range(len(directories)): directory = directories[directoryIndex] print('==> Analyzing directory %s'%(directory)) # grab the files, assume they're all midi numNotesOnInDirectory = 0 files = os.listdir(directory) for i in range(len(files)): if files[i] != '.DS_Store': totalFiles = totalFiles + 1 print('Processing file %g out of %g in directory: %s'%(i, len(files), files[i])) mid = MidiFile(directory + files[i]) curNumNotesOn = 0 for msg in mid: if (msg.type == 'note_on'): curNumNotesOn = curNumNotesOn + 1 print('%g Notes on in %s'%(curNumNotesOn, files[i])) numNotesOnInDirectory = numNotesOnInDirectory + curNumNotesOn else:
def __init__(self, *initial_data, **kwargs): np.random.seed(int(time.time())) # random seed for dictionary in initial_data: # allows for parameters to be loaded in as a dictionary for key in dictionary: setattr(gs, key, dictionary[key]) for key in kwargs: setattr(gs, key, kwargs[key]) self.start = time.time() # Launch PyGame pygame.init() pygame.mixer.init() pygame.display.set_caption(gs.GAME_TITLE) self.screen = pygame.display.set_mode( [gs.SCREEN_WIDTH, gs.SCREEN_HEIGHT]) # Initialize a few useful variables self.font = pygame.font.SysFont("calibri", 20) self.reward = 0 self.is_terminal = False self.count = +1 self.clock = pygame.time.Clock() self.score = "" self.note_count = 0 self.step_count = 0 self.midi_notes = [] if gs.USE_MIDI: if os.path.isdir(gs.MIDI_FILES_DIRECTORY): for file in os.listdir(gs.MIDI_FILES_DIRECTORY): if file.endswith('.midi') or file.endswith('.mid'): print("reading midi file: ", file) midiFile = MidiFile(gs.MIDI_FILES_DIRECTORY + '/' + str(file)) for i, track in enumerate(midiFile.tracks): for message in track: if message.type == "note_on": #print("note: " + str(message.note) + " time: " + str(message.time)) self.midi_notes.append( (message.note, message.time / gs.NOTE_SPEED)) self.penalty_zone = Penalty() self.penalty_list = pygame.sprite.Group() self.penalty_list.add(self.penalty_zone) self.all_items_list = pygame.sprite.Group() self.arm_sprite_list = pygame.sprite.Group() self.arm_list = [] self.note_list = pygame.sprite.Group() self.arm_actions = [] for i in range(gs.NUMBER_OF_ARMS): arm = Arm(i, self.arm_list, start=gs.ARM_STARTS[i]) self.arm_sprite_list.add(arm) self.all_items_list.add(arm) self.arm_actions.append(1) # 1 means move in default direction self.arm_list.append(arm) self.last_time = time.time()
#!/usr/bin/python import sys, getopt from mido import MidiFile f = raw_input("Enter a file (relative to this file's directory):") mid = MidiFile(f) for i, track in enumerate(mid.tracks): #track is <meta message s for msg in track: #msg is the message in form "note_on/off channel=0 note=# velocity=# time=# pass
import mido import operator from mido import MidiFile filename = 'test3' mid_in = MidiFile(filename + '_1.mid') #change time for i in range(0, len(mid_in.tracks) - 1, 1): t = 0 if mid_in.tracks[i][0].type == 'note_on' or mid_in.tracks[i][ 0].type == 'note_off' or mid_in.tracks[i][ 0].type == 'polytouch' or mid_in.tracks[i][ 0].type == 'control_change' or mid_in.tracks[i][ 0].type == 'program_change' or mid_in.tracks[i][ 0].type == 'aftertouch' or mid_in.tracks[i][ 0].type == 'pitchwheel': mid_in.tracks[i][0].channel = 0 for j in range(1, len(mid_in.tracks[i]) - 1, 1): t += mid_in.tracks[i][j].time mid_in.tracks[i][j].time = t if mid_in.tracks[i][0].type == 'note_on' or mid_in.tracks[i][ 0].type == 'note_off' or mid_in.tracks[i][ 0].type == 'polytouch' or mid_in.tracks[i][ 0].type == 'control_change' or mid_in.tracks[i][ 0].type == 'program_change' or mid_in.tracks[i][ 0].type == 'aftertouch' or mid_in.tracks[i][ 0].type == 'pitchwheel': mid_in.tracks[i][0].channel = 0 mid_out = MidiFile()
def print_midi(file): midi = MidiFile(file) for i, track in enumerate(midi.tracks): print('Track {}: {}'.format(i, track.name)) for msg in track: print(msg)
class PlayerThread(threading.Thread): global plyr_ctrls def __init__(self, _save_path, songfile, _plyr_ctrls): super(PlayerThread, self).__init__() self.name = 'Player' self.stoprequest = threading.Event() self.plyr_ctrls = _plyr_ctrls self.chan_roles = [0 for i in range(10)] self.plyr_ctrls['songfile'] = songfile self.midifile = MidiFile(_save_path + songfile) # 0 - drum fill self.counter = [0 for i in range(4)] self.wt = WolfTonesSong() self.save_path = _save_path self.load_song(songfile) self.alt_meas = [] #get the portname (system specific) env = socket.gethostname() if(env == 'record_synth'): names = str(mido.get_output_names()) ports = names.split(',') sobj = re.search(r'Synth input port \(\d*:0\)', ports[0], flags=0) portname = sobj.group() if(env == 'colinsullivan.me'): #dummy port for testing on a headless server with no audio portname = 'Midi Through:Midi Through Port-0 14:0' self.outport = mido.open_output(portname, autoreset=True) def join(self, timeout=None): logging.debug('Player joining..') self.outport.reset() self.stoprequest.set() super(PlayerThread, self).join(timeout) def set_save_path(self, path, temp = False): if(path): self.save_path = path if(temp): self.save_path = path + 'temp' def stop(self): self.plyr_ctrls['play'] = False def load_song(self, filename): self.stop() tmp = filename.split('.') # if you forget or are too lazy to type the filetype extenstion if(len(tmp) > 1 and tmp[-1] != 'mid'): filename += '.mid' songfile = self.save_path + filename self.wt.load_file(songfile) self.midifile = MidiFile(songfile) self.plyr_ctrls['songfile'] = filename #logging.debug(str(self.midifile.tracks)) # length of a quarter note self.ticks_per_beat = self.midifile.ticks_per_beat #self.chan_roles = [0 for i in range(10)] for trk in self.midifile.tracks: s = trk.name.split(':') chan = s[0] role = s[1] #logging.debug('read ' + chan + ' as ' + role) self.chan_roles[int(chan)] = role if(role[-3:] == '_ld'): logging.debug('making riff') self.make_riff(trk) logging.debug('Channel ' + str(chan) + ' is ' + role) def new_song(self): # save path here should be /songs/temp path = self.save_path fn = self.wt.get_by_genre(save_path=path) songfile = fn self.midifile = MidiFile(songfile) self.plyr_ctrls['songfile'] = songfile #logging.debug(str(self.midifile.tracks)) # length of a quarter note self.ticks_per_beat = self.midifile.ticks_per_beat #self.chan_roles = [0 for i in range(10)] for trk in self.midifile.tracks: s = trk.name.split(':') chan = s[0] role = s[1] #logging.debug('read ' + chan + ' as ' + role) self.chan_roles[int(chan)] = role ld_role = len(re.match('ld', role)) > 0 if(ld_role): logging.debug('making riff') self.make_riff(trk) logging.debug('Channel ' + str(chan) + ' is ' + role) def run(self): while(not self.stoprequest.isSet()): while(self.plyr_ctrls['play'] == True and not self.stoprequest.isSet()): #logging.debug('perc ' + str(self.plyr_ctrls['perc'])) #logging.debug('bass ' + str(self.plyr_ctrls['bass'])) was_playing = True ch_roles = self.chan_roles for msg in self.midifile.play(): if(self.plyr_ctrls['play'] == True and not self.stoprequest.isSet()): #-------------- MODIFY MIDI MESSAGES ON THE FLY ------------------------ # Here do things that only happen once when a value changes if(self.plyr_ctrls['val_chg'] == True): self.plyr_ctrls['val_chg'] = False pass if(msg.type == 'note_on' and msg.velocity): ctrl_vel = self.plyr_ctrls[ch_roles[msg.channel]] #logging.debug('ctrl_vel ' + str(ctrl_vel)) msg_vel = msg.velocity msg.velocity = self.get_scaled_velocity(msg_vel, ctrl_vel) if(self.plyr_ctrls['drum_fill']): if(ch_roles[msg.channel] == 'perc'): df_msg = msg.copy() df_msg.time = int(self.ticks_per_beat/16) df_msg.note = random.choice([35,36]) df_msg.velocity = self.get_scaled_velocity(msg.velocity, 110) self.outport.send(df_msg) if(self.plyr_ctrls['lead_fill']): continue role = ch_roles[msg.channel] #if(len(self.alt_meas) > 1 and role[-3:] == '_ld'): if(role[-3:] == '_ld'): logging.debug(len(self.alt_meas)) lf_msg = msg.copy() lf_msg = self.alt_meas[self.counter[1]] self.counter[1] += 1 if(self.counter[1] >= len(self.alt_meas)): self.counter[1] = 0 self.outport.send(lf_msg) ############ SEND MIDI MESSAGE ####################################### self.outport.send(msg) else: if(was_playing == True): self.outport.reset() was_playing = False break def get_scaled_velocity(self, msg_vel, ctrl_vel): ctrl_vel_ratio = float(ctrl_vel)/127 #logging.debug('msg_vel ' + str(msg_vel)) #logging.debug('ratio ' + str(ctrl_vel_ratio)) if(ctrl_vel_ratio == 0.5): rtn_vel = msg_vel elif(ctrl_vel_ratio > 0.5): rtn_vel = msg_vel + ((127 - msg_vel)*((ctrl_vel/64)-1)) elif(ctrl_vel_ratio < 0.5): rtn_vel = ctrl_vel_ratio * msg_vel * 2 #logging.debug('rtn_vel ' + str(rtn_vel)) return int(rtn_vel) def make_riff(self, track): ticks_sum = 0 msgs = [] self.alt_meas = [] if( not self.wt.scale): tmp_scale = [0,2,1,2,2,2,2,1] else: tmp_scale = self.wt.scale for i in range(36): rand_note = random.randint(0,len(tmp_scale)-1) steps = sum(tmp_scale[rand_note:-1]) logging.debug('steps ' + str(steps)) note = int(self.wt.key) + steps + random.randint(0,2)*12 len_note = [1,2,4,8,16] divisor = random.choice(len_note) time = int(self.ticks_per_beat/divisor) #logging.debug('note ' + str(self.wt.key)) #logging.debug('time ' + str(time)) #logging.debug('rand_note ' + str(rand_note)) msg = Message('note_on', note=60, time=100)
def showSampleInfo(input: str): from mido import MidiFile midi = MidiFile('music/sample/{}.mid'.format(input)) for i, t in enumerate(midi.tracks): print('Track: {}, Instrument: {}'.format(i, t.name))
import mido from mido import MidiFile output = mido.open_output() fileName = "~/Desktop/mbot.midi" for msg in MidiFile(fileName).play(): output.send(msg) print(msg)
def saveFile(self, filename): midi = MidiFile() midi.tracks.append(self.track) midi.ticks_per_beat = self.ticksPerBeat midi.save(filename)
from mido import Message, MidiFile, MidiTrack mid = MidiFile() track = MidiTrack() mid.tracks.append(track) track.append(Message('program_change', program=0, time=0)) # track.append(Message('note_on', note=64, velocity=64, time=32)) # track.append(Message('note_off', note=64, velocity=127, time=32)) i = 0 while i < 128: track.append(Message('note_on', note=i, velocity=96, time=0)) track.append(Message('note_off', note=i, velocity=96, time=3840)) print(i) i += 1 mid.save('0-127.mid')
#!/usr/bin/env python """ Create a new MIDI file with some random notes. The file is saved to test.mid. """ from __future__ import division import random import sys from mido import Message, MidiFile, MidiTrack, MAX_PITCHWHEEL notes = [64, 64+7, 64+12] outfile = MidiFile() track = MidiTrack() outfile.tracks.append(track) track.append(Message('program_change', program=12)) delta = 300 ticks_per_expr = int(sys.argv[1]) if len(sys.argv) > 1 else 20 for i in range(4): note = random.choice(notes) track.append(Message('note_on', note=note, velocity=100, time=delta)) for j in range(delta // ticks_per_expr): pitch = MAX_PITCHWHEEL * j * ticks_per_expr // delta track.append(Message('pitchwheel', pitch=pitch, time=ticks_per_expr)) track.append(Message('note_off', note=note, velocity=100, time=0)) outfile.save('test.mid')
midiFile = 'SuperSmashBrosUltimate.mid' # Other startup stuff send = "\n" time.sleep(3) # Sends code to Arduino def sendLine(code): print(int(code)) ser.write((code + "\n").encode()) # ser.write(send.encode()) # Opens and reads Midi file for msg in MidiFile(midiFile): time.sleep(msg.time * 0.8) if not msg.is_meta: data = str(msg) # Filters out other initializing stuff if data[0:4] == "note": # If drive should turn on if data[6:7] == "n": if data[16] == "0": code = ("3" + str(hertz[int(data[23:25])]) + "1") sendLine(code) else: code = ("2" + str(hertz[int(data[23:25])]) + "1") sendLine(code)
Play MIDI file on output port. Run with (for example): ./play_midi_file.py 'SH-201 MIDI 1' 'test.mid' """ import sys import mido import time from mido import MidiFile filename = sys.argv[1] if len(sys.argv) == 3: portname = sys.argv[2] else: portname = None with mido.open_output(portname) as output: try: midifile = MidiFile(filename) t0 = time.time() for message in midifile.play(): print(message) output.send(message) print('play time: {:.2f} s (expected {:.2f})'.format( time.time() - t0, midifile.length)) except KeyboardInterrupt: print() output.reset()
# from Generative Music's Class 2 Code from mido import MidiFile file_name = '21_knives_out' mid = MidiFile('dataset/radiohead/' + file_name + '.mid') # look at the track names for i, track in enumerate(mid.tracks): print((i, track.name)) # create array of notes notes = [] messages = [] for message in mid.tracks[7]: messages.append(message) for m in range(len(messages)): # print messages[m] note = "" time = "" if messages[m].type == 'note_on': message_components = str(messages[m]).split(' ') for item in message_components: if 'note=' in item: # notes.append(item.split('note=')[1]) note = item.split('note=')[1] message_components = str(messages[m + 1]).split(' ') for item in message_components: if 'time=' in item: time = item.split('time=')[1] if note != "": notes.append(str(note + "_" + time))
if len( sys.argv ) > 3: samplerate = int(sys.argv[3]) win_s = 512 // downsample # fft size hop_s = 256 // downsample # hop size s = source(filename, samplerate, hop_s) samplerate = s.samplerate tolerance = 0.8 notes_o = notes("default", win_s, hop_s, samplerate) print("%8s" % "time","[ start","vel","last ]") # create a midi file mid = MidiFile() track = MidiTrack() mid.tracks.append(track) ticks_per_beat = mid.ticks_per_beat # default: 480 bpm = 120 # default midi tempo tempo = bpm2tempo(bpm) track.append(MetaMessage('set_tempo', tempo=tempo)) track.append(MetaMessage('time_signature', numerator=4, denominator=4)) def frames2tick(frames, samplerate=samplerate): sec = frames / float(samplerate) return int(second2tick(sec, ticks_per_beat, tempo)) last_time = 0
def main(): # key sig-time pairs global shortPhrases global longPhrases directory = input("Please enter a path to the desired directory: ") for filename in os.listdir(directory): if filename.endswith(".midi") or filename.endswith(".mid"): # print("FileName: ", filename) mid = MidiFile("MidiDataset/"+filename) key_sig = '' time_sig = '' numTicksBerBeat = 0 shortPhraseList = [] longPhraseList = [] ticksSoFar = 0 numerator = 0 # will be numerator of time signature denominator = 0 # will be denominator of time signature for i, track in enumerate(mid.tracks): for msg in track: if msg.is_meta and msg.type == 'key_signature': key_sig = msg.key if msg.is_meta and msg.type == 'time_signature': numerator = msg.numerator # print("Numerator:", numerator) denominator = msg.denominator # print("denominator:", denominator) # clocks per click = midi clock ticks per metronome beat clocks_per_click = msg.clocks_per_click notated_32nd_notes_per_beat = msg.notated_32nd_notes_per_beat time_sig = str(numerator) + " / " + str(denominator) numTicksBerBeat = clocks_per_click * notated_32nd_notes_per_beat if key_sig != '' and time_sig != '': keyTimePair = (key_sig, time_sig) # print("KeyTimePair: ", keyTimePair) if keyTimePair not in shortPhrases: shortPhrases[keyTimePair] = [] if keyTimePair not in longPhrases: longPhrases[keyTimePair] = [] if msg.is_meta == False and numerator != 0 and numTicksBerBeat != 0: # generating phrases if msg.type == "note_on" or msg.type == "note_off": time = msg.time ticksSoFar += int(time) shortPhraseList.append(msg) longPhraseList.append(msg) if ticksSoFar % (numTicksBerBeat * int(numerator) * 4) == 0: # long phrase ticksSoFar = 0 # print("Long Phrase:", longPhraseList) # print() longPhrases[keyTimePair].append(longPhraseList) longPhraseList.clear() # if ticksSoFar % (numTicksBerBeat * int(numerator)) == 0: # short phrases if ticksSoFar % (numTicksBerBeat * int(numerator)) == 0: # short phrases # print("Short Phrase:", shortPhraseList) # print() shortPhrases[keyTimePair].append(shortPhraseList) shortPhraseList.clear() # print("Short Phrases Dict: ", len(shortPhrases)) # print("Long Phrases Dict: ", len(longPhrases)) # test plays random long phrase (supposed to be 4 bars) in the key of C, 4/4 time rndLong = random.randrange(len(longPhrases[('C', '4 / 4')])) output = mido.open_output('IAC Driver Bus 1') test = toFile(longPhrases[('C', '4 / 4')][rndLong], 'C', '4 / 4', 375000, False) for msg in test.play(): print(msg) output.send(msg)
from mido import MidiFile, MidiTrack, Message from keras.layers import LSTM, Dense, Activation, Dropout from keras.preprocessing import sequence from keras.models import Sequential, load_model from keras.optimizers import RMSprop from keras.callbacks import ModelCheckpoint import numpy as np import mido import os ########### PROCESS MIDI FILE ############# notes = [] #count = 10 for filename in os.listdir('data/train/'): mid = MidiFile('data/train/'+filename) for msg in mid: if not msg.is_meta: if msg.type == 'note_on': note = msg.bytes() note[0] = msg.channel note.append(msg.time) notes.append(note) # count -=1 # if count == 0: break tr_size = len(notes) ########################################### ######## SCALE DATA TO BETWEEN 0, 1 #######
import sys from mido import Message, MetaMessage, MidiFile, MidiTrack mid = MidiFile(type=0) track = MidiTrack() mid.tracks.append(track) note = 46 track.append(Message('program_change', program=0, time=0)) track.append(Message('note_on', note=note, velocity=100, time=0)) track.append(Message('note_off', note=note, velocity=100, time=900)) mid.save( '/Users/scott.cook/PycharmProjects/MindVST/samples/midi_files/midi_As3_900ms.mid' ) filename = '/Users/scott.cook/PycharmProjects/MindVST/samples/midi_files/midi_As3_900ms.mid' midi_file = MidiFile(filename) for i, track in enumerate(midi_file.tracks): sys.stdout.write('=== Track {}\n'.format(i)) for message in track: sys.stdout.write(' {!r}\n'.format(message))
from mido import MidiFile, MidiTrack, Message import random mid = MidiFile(type=0) track = MidiTrack() mid.tracks.append(track) notes = range(40, 90) for i in range(20): note = random.choice(notes) track.append(Message('note_on', note=note, velocity=100, time=i*100)) track.append(Message('note_off', note=note, velocity=100, time=(i+1)*100)) mid.save('random.mid')
parser.add_argument("-d","--dataPath", required=True, help="The path to the data that trained the model, to sigure out std and means to map back to original distrib") parser.add_argument("-r","--ranges", required=True, metavar='range', nargs='+', help="The ranges in timesteps to imagine e.g. \"128:160\", \"200:280\" ") # metavar='N', type=int, nargs='+' parser.add_argument("-o","--outputMidi", help="The path to the output midi, if not given it will be assumed from input and model") args = parser.parse_args() #read in input midi file_path = args.inputMidi tokens = file_path.split("/") file_name = tokens[len(tokens)-1] file_name_no_ext = file_name.split(".")[0] mid = MidiFile(file_path) timeseries_tensor = utl.convert_midi_to_time_series(mid,5,5,8) net = None if args.networkType == "ConvNet_1_0_2": net = m.ConvNet_1_0_2().load_from_checkpoint(args.networkPath) elif args.networkType == "TransformerNet_1_0_2": net = m.TransformerNet_1_0_2().load_from_checkpoint(args.networkPath) else: print("Not supported type!") sys.exit() net.eval()
def write_midi(pr, quantization, write_path, tempo=80): def pr_to_list(pr): # List event = (pitch, velocity, time) T, N = pr.shape t_last = 0 pr_tm1 = np.zeros(N) list_event = [] for t in range(T): pr_t = pr[t] mask = (pr_t != pr_tm1) if (mask).any(): for n in range(N): if mask[n]: pitch = n velocity = int(pr_t[n]) # Time is incremented since last event t_event = t - t_last t_last = t list_event.append((pitch, velocity, t_event)) pr_tm1 = pr_t return list_event # Tempo microseconds_per_beat = mido.bpm2tempo(tempo) # Write a pianoroll in a midi file mid = MidiFile() # ticks_per_beat can be the quantization, this simplify the writing process mid.ticks_per_beat = quantization # Each instrument is a track for instrument_name, matrix in pr.iteritems(): # A bit shity : if the pr is a binary pr, multiply by 127 if np.max(matrix) == 1: matrix = matrix * 127 # Add a new track with the instrument name to the midi file track = mid.add_track(instrument_name) # transform the matrix in a list of (pitch, velocity, time) events = pr_to_list(matrix) # Tempo track.append(mido.MetaMessage('set_tempo', tempo=microseconds_per_beat)) # Add the program_change try: program = program_change_mapping[instrument_name] except: # Defaul is piano print instrument_name + " not in the program_change mapping" print "Default value is 1 (piano)" print "Check acidano/data_processing/utils/program_change_mapping.py" program = 1 track.append(mido.Message('program_change', program=program)) # This list is required to shut down # notes that are on, intensity modified, then off only 1 time # Example : # (60,20,0) # (60,40,10) # (60,0,15) notes_on_list = [] # Write events in the midi file for event in events: pitch, velocity, time = event if velocity == 0: # Get the channel track.append(mido.Message('note_off', note=pitch, velocity=0, time=time)) notes_on_list.remove(pitch) else: if pitch in notes_on_list: track.append(mido.Message('note_off', note=pitch, velocity=0, time=time)) notes_on_list.remove(pitch) time = 0 track.append(mido.Message('note_on', note=pitch, velocity=velocity, time=time)) notes_on_list.append(pitch) mid.save(write_path) return
ultimate = notes[-1][0] # rand = random.choice([ultimate, octave(ultimate)]) queue[-1] = [[ultimate], notes[-1][1], 'unison'] # for i in range(len(queue)): # print(queue[i]) # batch_notes(queue[i][0], queue[i][1], 0, 1) return queue if __name__ == "__main__": # test = MidiFile('test1.mid') # print_midi(test) mid = MidiFile() # t = MidiTrack() # t.append(Message('program_change', program=12, time=0)) # t.append(Message('note_on', note=59, velocity=64, time=0)) # t.append(Message('note_off', note=59, velocity=64, time=beats_to_ticks(2))) track.append(Message('program_change', program=12, time=0)) # test = MidiFile('test3.mid') # # notes = get_notes(test) # # fscp = first_species(notes) # # for i in range(len(fscp)): # # print(fscp[i]) # # batch_notes(fscp[i][0], fscp[i][1], 0, 1)
#!/usr/bin/env python import mido from mido import Message, MidiFile import time infile = MidiFile('new_song.mid') output = mido.open_output() for msg in infile.play(): output.send(msg)
from mido import MidiFile from mido.midifiles import MidiTrack from mido import Message, MetaMessage import time import datetime with MidiFile() as new_mid: new_track = MidiTrack() filename = "generated-music/round2-2.txt" with open(filename) as f: new_track.append(MetaMessage('set_tempo', tempo=500000 * 3)) for line in f: parts = line.split() #c~0 n!1 v@2 t#3 if parts[0] == "pw": if abs(int(float(parts[2].split('=')[1]))) < 8191: new_track.append( Message('pitchwheel', channel=0, pitch=int(float(parts[1].split('*')[1])), time=int(float(parts[2].split('#')[1])))) elif parts[0] == "no": velocity = int(float(parts[2].split('%')[1])) velocity = velocity if velocity <= 127 else 127 t = int(float(parts[3].split('#')[1])) t = t if t <= 127 else 127 new_track.append(
def file_inp(self): self.file = askopenfilename(initialdir= os.getcwd(), filetypes = (("Mid files","*.mid"), ("Wav files","*.wav"), ("all files","*.*"))) if str(self.file).strip('()') != str(): self.lbl_title = Label(self.master, text=self.file.split('/')[-1][:25], font=("Arial", 10), width=20) self.lbl_title.grid(column=3, row=0, sticky="ew") if self.file.split('.')[-1] == 'mid': duration_secs = int(MidiFile(self.file).length) elif self.file.split('.')[-1] == 'wav': source_rate, source_sig = wav.read(self.file) duration_secs = int(len(source_sig) / float(source_rate)) else: pass self.progressbar.config(mode = 'determinate', maximum = duration_secs*2+1, value = 0) self.progressbar.step(0) if self.file.split('.')[-1] == 'wav': self.batch = 5000 _, self.music_freq = wav.read(self.file) elif self.file.split('.')[-1] == 'mid': mid_file = converter.parse(self.file) self.music_freq = [0, ] for e in mid_file: for f in e: if type(f)==note.Note: self.music_freq = self.music_freq + [int(f.pitch.frequency)] elif type(f)==note.Rest: self.music_freq = self.music_freq + [0] elif type(f)==chord.Chord: for g in f.pitches: self.music_freq = self.music_freq + [int(g.frequency)] elif type(f)==stream.Voice: for g in f.notes: if type(g)==note.Note: self.music_freq = self.music_freq + [int(g.pitch.frequency)] elif type(g)==note.Rest: self.music_freq = self.music_freq + [0] elif type(g)==chord.Chord: for h in g.pitches: self.music_freq = self.music_freq + [int(h.frequency)] else: pass else: pass lgth = len(self.music_freq) for i in range(1, lgth): self.music_freq.insert(lgth-i+1, -self.music_freq[lgth-i]) duration = int(MidiFile(self.file).length) self.batch = int(len(self.music_freq) / duration / 2) else: self.batch = 5000 self.music_freq = array([0 for x in range(self.batch)]) else: pass
print("Writing file...") with open('single.csv', 'w') as f_handle: np.savetxt(f_handle, et_sample, fmt='%d', delimiter=",") np.savetxt(f_handle, mid_sample, fmt='%d', delimiter=",") num_midi += 1 return 1 # # begin main body of code # #mid = MidiFile(str(sys.argv[1])) mid = MidiFile("KennyCB2.mid") print("ticks: ", mid.ticks_per_beat) for i, track in enumerate(mid.tracks): #print('Track {}: {}'.format(i, track.name)) # check for cases where there is more than 1 track, we don't want this if i > 1: print("Error: More than one track found.") break # go through each midi message in the track for message in track: if (message.type == 'set_tempo'): tempo = message.tempo
from mido import MidiFile import mido output = mido.open_output() output.send(mido.Message('note_on', note = 60, velocity=64)) with input as mido.open_input('SH-201'): for message in input: print(message) from mido import MidiFile for message in MidiFile('song.mid').play(): output.send(message) p = mido.Parser() p.feed([0x90, 0x40]) p.feed_byte(0x60) p.pending() for message in p: print(message) #note_on channel=0 note=64 velocity=96 time=0 for message in MidiFile('song.mid').play(): port.send(message) from mido import Message
#!/usr/bin/python from mido import MidiFile import sys if len(sys.argv) != 2: print "Usage: {0} <midifile>".format(sys.argv[0]) sys.exit(2) midifile = sys.argv[1] print "# Translating {}".format(midifile) msgqueue = MidiFile(midifile) timenow = 0.1 timeoffset = -1 channelmap = [2, 1, 0, 3, 4] channels = ["pedal", "great", "swell", "choir", "posit"] notes_on = [0, 0, 0, 0, 0] notes_off = [0, 0, 0, 0, 0] outputlist = [] for msg in msgqueue: timenow += msg.time if msg.type == "note_on" and msg.velocity > 0: if timeoffset < 0: timeoffset = timenow - 0.1 payload = "N {} {} 1 ".format(channelmap[msg.channel], msg.note) target = "{:09.3f}:{}".format(timenow - timeoffset, channels[channelmap[msg.channel]]) outputlist.append((target, payload)) notes_on[channelmap[msg.channel]] += 1
#dependencies import mido from mido import MidiFile, MidiTrack, Message from keras.layers import LSTM, Dense, Activation, Dropout, Flatten from keras.preprocessing import sequence from keras.models import Sequential from keras.optimizers import Adam from keras.callbacks import ModelCheckpoint from sklearn.preprocessing import MinMaxScaler import numpy as np #reading the midi files #try just 1 first mid = MidiFile('./jazz_data/4thAvenueTheme.mid') notes = [] #extract note sequences notes = [] for msg in mid: if not msg.is_meta and msg.channel == 0 and msg.type == 'note_on': data = msg.bytes() notes.append(data[1]) scaler = MinMaxScaler(feature_range=(0, 1)) scaler.fit(np.array(notes).reshape(-1, 1)) notes = list(scaler.transform(np.array(notes).reshape(-1, 1))) #Prepare features for training and data subsample for prediction # LSTM layers requires that data must have a certain shape # create list of lists fist
print(*args, **kwargs) else: vprint = lambda *a, **k: None #do-nothing function # Get import and export folder locations dom = parse(ardourFile) sessionName = dom.getElementsByTagName("Session")[0].getAttribute("name") dir = os.path.dirname(ardourFile) importFolder = os.path.join(dir, "interchange", sessionName, "midifiles") exportFolder = os.path.join(dir, "export") vprint(importFolder, exportFolder) # Iterate through the MIDI tracks in Ardour (called "Routes" in the XML file) # Gets Ardour track id's and saves track names mid = MidiFile(type=1, ticks_per_beat=19200) trackRef = {} #ardour-track-id : midi-track-id i = 0 for route in dom.getElementsByTagName("Route"): if route.getAttribute("default-type") == "midi": rname = route.getAttribute("name") if args.omitparens: p = re.compile("(.*)(\(.*\))(.*)") rname = p.sub(r"\1\3", rname).strip() mid.add_track(name=rname) mid.tracks[i].append(MetaMessage("instrument_name", name=rname)) programNumber = getGeneralMidiNumber(rname) if programNumber == -10: mid.tracks[i].append( MetaMessage("channel_prefix", channel=10, time=0)) if args.musescore:
class CSVParser: def __init__(self, csv_file, deltaT): self.deltaT = deltaT self.csv_file = csv_file # default values cause yolo self.ticks_per_beat = 384 self.tempo = 512820 self.active_notes = [None] * 127 self.mid = MidiFile(ticks_per_beat=self.ticks_per_beat) self.track = MidiTrack() self.mid.tracks.append(self.track) self.set_meta_tempo() self.last_note_time = 0 def set_tempo(self, tempo): self.tempo = tempo def ms2sec(self, ms): return self.deltaT / 1000. def seconds2ticks(self, seconds): return second2tick(seconds, self.ticks_per_beat, self.tempo) def ticks2seconds(self, ticks): return tick2second(ticks, self.ticks_per_beat, self.tempo) def parse_row(self, row, index): notes = row.split(',') notes = map(int, notes) is_first = True for i in range(0, len(notes)): if notes[i] != 0: if self.active_notes[i] is None: self.active_notes[i] = True ticks = 0 if is_first: ticks = self.seconds2ticks(index * self.ms2sec( self.deltaT)) - self.last_note_time self.last_note_time = self.seconds2ticks( index * self.ms2sec(self.deltaT)) is_first = False self.note_on(i, notes[i], int(ticks)) else: if self.active_notes[i]: ticks = 0 if is_first: ticks = self.seconds2ticks(index * self.ms2sec( self.deltaT)) - self.last_note_time self.last_note_time = self.seconds2ticks( index * self.ms2sec(self.deltaT)) is_first = False self.note_off(i, int(ticks)) self.active_notes[i] = None def set_last_note(self, ticks): self.last_note_time = ticks def note_on(self, note, intensity, delta_ticks): self.track.append( Message('note_on', note=note, velocity=intensity, time=delta_ticks)) def note_off(self, note, delta_ticks): self.track.append( Message('note_off', note=note, velocity=64, time=delta_ticks)) def set_meta_tempo(self): self.track.append(MetaMessage('set_tempo', tempo=self.tempo)) def convert(self): with open(self.csv_file, 'r') as f: i = 0 for line in f: self.parse_row(line, i) i += 1 def save(self): self.mid.save(self.csv_file[:-4] + 'FromCSV.mid')
def music(Key=0, BPM=0, Chord_prog=[0], beat=[0], song_name='new_song.mid', arpeggio=False, duree=8, instrumentbass=0, instrumentmain=0, probjump=0, probautocorr=0, probnextchordnote=0): print(duree) if Key == 0: Key = rd.randrange(36, 49) if BPM == 0: BPM = rd.randrange(50, 400) tempo = 60000 / BPM if Chord_prog == [0]: Chord_prog = cpg() Chord_roots = chord_root(Chord_prog) if beat == [0]: beat = bg_seq_combine(duree // 2) if instrumentbass == 0: instrumentbass = rd.randrange(0, 121) if instrumentmain == 0: instrumentmain = rd.randrange(0, 121) if probjump == 0: probjump = rd.randrange(1, 10) if probautocorr == 0: probautocorr = rd.random() if probnextchordnote == 0: probnextchordnote = rd.random() print('Chord progression:', Chord_prog, ', Key:', Key, ', BPM:', BPM, ', Beat:', beat) mid = MidiFile() track1 = MidiTrack() track2 = MidiTrack() track3 = MidiTrack() track4 = MidiTrack() melody = MidiTrack() mid.tracks.append(track1) mid.tracks.append(track2) mid.tracks.append(track3) mid.tracks.append(track4) mid.tracks.append(melody) track1.append(Message('program_change', program=instrumentbass, time=2)) track2.append(Message('program_change', program=instrumentbass, time=2)) track3.append(Message('program_change', program=instrumentbass, time=2)) track4.append(Message('program_change', program=instrumentbass, time=2)) melody.append(Message('program_change', program=instrumentmain, time=2)) refrain = songbloc(Chord_prog, duree, couplet=0) couplet = songbloc(Chord_prog, duree, couplet=1) if Chord_prog[0] == 1: bridge_chords = cpg(starting_value=[2, 3, 6][rd.randrange(0, 3)]) else: bridge_chords = cpg(starting_value=[1, 4, 5][rd.randrange(0, 3)]) bridge = songbloc(bridge_chords, duree / 2, couplet=0) #### intro (melodie vide) melody.append(Message('note_on', note=32, velocity=0, time=0)) melody.append( Message('note_off', note=32, velocity=127, time=int(4 * 8 * tempo))) melodie_tot = couplet[0] + refrain[0] + couplet[0] + refrain[0] + refrain[ 0] #+bridge[0]+bridge[0]+refrain[0]+refrain[0] list_list_temps = couplet[1] + refrain[1] + couplet[1] + refrain[ 1] + refrain[1] #+bridge[1]+bridge[1]+refrain[1]+refrain[1] # melodie_tot = bridge[0] # list_list_temps = bridge[1] print(melodie_tot) loop = 1 flat_list_temps = [] for sublist in list_list_temps: for item in sublist: flat_list_temps.append(item) print(flat_list_temps) for j in range(loop): for i in range(len(flat_list_temps)): lanote = Key + 12 + melodie_tot[i] temps = int(flat_list_temps[i] * tempo) melody.append( Message('note_on', note=lanote, velocity=rd.randrange(-20, 20) + 64, time=0)) melody.append( Message('note_off', note=lanote, velocity=127, time=temps)) muted_beat = [[rd.randrange(0, 2) for x in range(len(beat))] for y in range(4)] random_arpeggio = rd.randrange(0, 3) print(muted_beat) for x in range(4): for i in Chord_roots: if arpeggio == True or random_arpeggio == 1: arpChord2(Key + i, tempo, track1) if duree == 8: arpChord2(Key + i, tempo, track1) else: Chord(Key + i, tempo, track1, beat, velocity=muted_beat[0]) Chord(Key + i + 7, tempo, track2, beat, velocity=muted_beat[1]) Chord(Key + i + 12, tempo, track3, beat, velocity=muted_beat[2]) if i in [0, 5, 7]: Chord(Key + i + 4, tempo, track4, beat, velocity=muted_beat[3]) else: Chord(Key + i + 3, tempo, track4, beat, velocity=muted_beat[3]) # for x in range(2): # for i in chord_root(bridge_chords): # if arpeggio == True or random_arpeggio==1: # arpChord2(Key + i, tempo, track1) # if duree//2 == 8: # arpChord2(Key + i, tempo, track1) # else: # Chord(Key + i, tempo, track1, beat, velocity=muted_beat[0]) # Chord(Key + i + 7, tempo, track2, beat, velocity=muted_beat[1]) # Chord(Key + i + 12, tempo, track3, beat, velocity=muted_beat[2]) # # if i in [0, 5, 7]: # Chord(Key + i + 4, tempo, track4, beat, velocity=muted_beat[3]) # else: # Chord(Key + i + 3, tempo, track4, beat, velocity=muted_beat[3]) for x in range(3): for i in Chord_roots: if arpeggio == True or random_arpeggio == 1: arpChord2(Key + i, tempo, track1) if duree == 8: arpChord2(Key + i, tempo, track1) else: Chord(Key + i, tempo, track1, beat, velocity=muted_beat[0]) Chord(Key + i + 7, tempo, track2, beat, velocity=muted_beat[1]) Chord(Key + i + 12, tempo, track3, beat, velocity=muted_beat[2]) if i in [0, 5, 7]: Chord(Key + i + 4, tempo, track4, beat, velocity=muted_beat[3]) else: Chord(Key + i + 3, tempo, track4, beat, velocity=muted_beat[3]) #fin #arpChord2(Key + Chord_roots[0], tempo, track1) tempo = int(tempo) track1.append( Message('note_on', note=Key + Chord_roots[0] - 12, velocity=(rd.randrange(-20, 20) + 40), time=0)) track1.append( Message('note_off', note=Key + Chord_roots[0] - 12, velocity=127, time=tempo * 4)) track2.append( Message('note_on', note=Key + Chord_roots[0] + 7 - 12, velocity=(rd.randrange(-20, 20) + 40), time=0)) track2.append( Message('note_off', note=Key + Chord_roots[0] + 7 - 12, velocity=127, time=tempo * 4)) track3.append( Message('note_on', note=Key + Chord_roots[0], velocity=(rd.randrange(-20, 20) + 40), time=0)) track3.append( Message('note_off', note=Key + Chord_roots[0], velocity=127, time=tempo * 4)) if Chord_roots[0] in [0, 5, 7]: track4.append( Message('note_on', note=Key + Chord_roots[0] + 4 - 12, velocity=(rd.randrange(-20, 20) + 40), time=0)) track4.append( Message('note_off', note=Key + Chord_roots[0] + 4 - 12, velocity=127, time=tempo * 4)) else: track4.append( Message('note_on', note=Key + Chord_roots[0] + 3 - 12, velocity=(rd.randrange(-20, 20) + 40), time=0)) track4.append( Message('note_off', note=Key + Chord_roots[0] + 3 - 12, velocity=127, time=tempo * 4)) attributs = { 'Chord_progression': [Chord_prog], 'Song_name': song_name, 'Key': Key, 'BPM': BPM, 'Beat': [beat], 'is_arpeggio': arpeggio == True or random_arpeggio == 1, 'Melody': [melodie_tot], 'Muted_beat': [muted_beat], 'list_temps': [list_list_temps], # 'probability_pause':Average(list_prob_pause), # 'probability_2':Average(list_prob_2), # 'probability_1':Average(list_prob_1), # 'probability_05':Average(list_prob_05), 'probability_jump': probjump, 'probability_autocorrelation': probautocorr, 'probability_next_chord_note': probnextchordnote, 'instrument_bass': instrumentbass, 'instrument_main': instrumentmain } data = pd.DataFrame(attributs, columns=[ 'Chord_progression', 'Song_name', 'Key', 'BPM', 'Beat', 'is_arpeggio', 'Melody', 'Muted_beat', 'list_temps', 'probability_jump', 'probability_autocorrelation', 'probability_next_chord_note', 'instrument_bass', 'instrument_main' ]) #'probability_pause', 'probability_2', 'probability_1', 'probability_05', mid.save(song_name) return (data)
def midi_to_csv(midi_file, sampling_t, output_t): mid = MidiFile(midi_file) parser = NoteParser(mid, mid.ticks_per_beat, sampling_t, output_t) parser.parse()
def __init__(self, music_dir): log(INFO, 'Setting up MIDI reader') self.files = [] self.files_count = 0 self.play_in_progress = False self.play_file_index = -1 self.play_event_index = -1 log(INFO, 'Scanning {} directory for MIDI files'.format(music_dir)) for dirname, dirnames, filenames in sorted(os.walk(music_dir)): for filename in sorted(filenames): fullname = os.path.join(dirname, filename) data = MidiFile(fullname, clip=True) tempo = midi.get_midi_file_tempo(data) events = midi.get_midi_file_events(data) length = int(data.length) if data.type == 2: log( WARNING, 'Dropping {}, as of unsupported MIDI type 2'.format( filename)) elif tempo == 0: log( WARNING, 'Dropping {}, as no valid tempo was found'.format( filename)) elif len(events) == 0: log( WARNING, 'Dropping {}, as no events were found'.format( filename)) else: file_data = {} file_data['name'] = filename file_data['tempo'] = tempo file_data['length'] = length file_data['events'] = events file_data['events_count'] = len(events) log( INFO, 'Registered file #{}: {}'.format( self.files_count, filename)) self.files.append(file_data) self.files_count += 1 log(INFO, 'Found & parsed {} MIDI files'.format(self.files_count)) return
class Player: def __init__(self, queue=Queue(), running=Value('i', False), tempo=Value('i', default_tempo), deadline=Value('f', 0)): self.midiout = MidiOut() self.midi_for_file = MidiFile() self.last_chord = empty_chord self.queue_out = queue self.running = running self.tempo = tempo self.deadline = deadline self.start_peak = Value('f', 0) self.start_chord = 0 def play_peak(self, number=default_peak_number, velocity=default_peak_velocity): note_on = Message('note_on', note=number, velocity=velocity, channel=default_ultrasound_channel).bytes() self.midiout.send_message(note_on) sleep(default_peak_time) note_off = Message('note_off', note=number, velocity=min_velocity, channel=default_ultrasound_channel).bytes() self.midiout.send_message(note_off) def play_chord_same_time(self): chord = self.queue_out.get() # print("player get", chord, "vel", chord.velocity, "queue", self.queue_out.qsize(), "time", time.monotonic()) if chord.velocity > 127: chord.velocity = 127 if chord.duration == 0: return for note in chord.notes: if note.number > 127: print("an incorrect note in player") return if self.last_chord != empty_chord: for note in self.last_chord.notes: note_off = Message('note_off', note=note.number, velocity=min_velocity, channel=default_channel).bytes() self.midiout.send_message(note_off) for note in chord.notes: note_on = Message('note_on', note=note.number, velocity=chord.velocity, channel=default_channel).bytes() self.midiout.send_message(note_on) self.last_chord = chord sleep(len_in_s(chord.duration, self.tempo.value)) if self.last_chord == chord: for note in chord.notes: note_off = Message('note_off', note=note.number, velocity=min_velocity, channel=default_channel).bytes() self.midiout.send_message(note_off) def play_chord_arpeggio(self, track=np.array([])): chord = self.queue_out.get() print("player get", chord, "vel", chord.velocity, "queue", self.queue_out.qsize(), "time", time.monotonic()) if chord.velocity > 127: chord.velocity = 127 if chord.duration == 0: return for note in chord.notes: if note.number > 127: print("an incorrect note in player") return chord.notes = sorted(chord.notes) if len(chord.notes) == 3: chord.notes.append(Note(chord.notes[0].number + 12)) if track == np.array([]): notes_numbers = np.arange(len(chord.notes)) notes_durations = np.array( [int(128 / len(chord.notes)) for i in range(len(chord.notes))]) track = np.column_stack((notes_numbers, notes_durations)) notes_sum_durations = np.cumsum(track.transpose(), axis=1)[1] if self.last_note_number is not None: note_off = Message('note_off', note=self.last_note_number, velocity=min_velocity, channel=default_channel).bytes() self.midiout.send_message(note_off) self.start_chord = time.monotonic() pair = 0 note_number = track[pair][0] note_on = Message('note_on', note=chord.notes[note_number].number, velocity=chord.velocity, channel=default_channel).bytes() self.midiout.send_message(note_on) while (pair < len(track) - 1): # TODO if time.monotonic() > self.start_chord + max( (self.deadline.value - self.start_chord) * notes_sum_durations[pair] / notes_sum_durations[-1], len_in_s(notes_sum_durations[pair], self.tempo.value)): note_off = Message('note_off', note=chord.notes[note_number].number, velocity=min_velocity, channel=default_channel).bytes() self.midiout.send_message(note_off) pair += 1 note_number = track[pair][0] note_on = Message('note_on', note=chord.notes[note_number].number, velocity=chord.velocity, channel=default_channel).bytes() self.midiout.send_message(note_on) self.last_note_number = chord.notes[note_number].number time.sleep(0.01) def put(self, chord): if type(chord) == Chord: self.queue_out.put(chord) return True return False def set_up_ports(self): """ This is necessary to HEAR the music """ available_ports = self.midiout.get_ports() if available_ports: self.midiout.open_port(default_port) else: self.midiout.open_virtual_port("Tmp virtual output") def set_up_instrument(self, program=default_instrument): program_change = Message('program_change', program=program, channel=default_channel).bytes() self.midiout.send_message(program_change) def set_up_ultrasound_instrument(self, program=default_ultrasound_instrument): program_change = Message('program_change', program=program, channel=default_ultrasound_channel).bytes() self.midiout.send_message(program_change) def set_up_midi_for_file(self): self.midi_for_file.tracks.append(MidiTrack()) def set_tempo(self, tempo=default_tempo): self.tempo.value = tempo def set_deadline(self, deadline=0): self.deadline.value = deadline def set_start_peak(self, start=max_time): self.start_peak.value = start def get_sleeping_time(self): return self.deadline.value - time.monotonic() def get_track(self): return self.midi_for_file.tracks[0] def save_file(self, filename='my track.mid'): self.midi_for_file.save(filename) return filename def run(self): self.running.value = True self.set_up_ports() self.set_up_midi_for_file() self.set_up_instrument() self.set_up_ultrasound_instrument() self.queue_process = Process(target=run_queue_out, args=(self, )) self.queue_process.start() self.queue_process = Process(target=run_peak, args=(self, )) self.queue_process.start() def stop(self): """ All chords that already sound will continue to sound """ self.running.value = False self.queue_process.join() self.queue_process.join() self.queue_out = Queue() queue_out = None running = None tempo = None deadline = None start_peak = None start_chord = None queue_process = None peak_process = None midiout = None midi_for_file = None last_chord = None last_note_number = None
def load_midi_file(files_mid): mid = MidiFile(files_mid, clip=False) if (mid.length >= 30): return mid else: return 0
#import mido from mido import MidiFile mid = MidiFile('../Melancholy_-_Piano_Solo_Arrangement.mscz.mid') print(mid) for i, track in enumerate(mid.tracks): print('Track {}: {}'.format(i, track.name)) for msg in track: print(msg)
def runModel(): if not args.train: if args.conv: model = createConvModel() else: model = createLSTMModel() model.load_weights(args.load_weights) #start with some random notes to generate off of ls = [] for x in range(lengthSample): ls.append(random.randint(0, dataInd.shape[0])) #set up midi file mid = MidiFile() track = MidiTrack() mid.tracks.append(track) track.append(Message('program_change', program=12)) time = 0 #run for 10 seconds while time < 10.: print(str(ls[-5:]) + " " + str(time)) #predict res = model.predict( np.expand_dims(np.array(ls[-lengthSample:]), axis=0))[0] listAdd = res #convert to note res = indToNote(np.argmax(np.array(res))) time += res[2] res[0] = np.rint(res[0]) res[1] = np.rint(res[1] * 127) res[2] = np.rint(res[2] * 880) if (res[0] > 0): track.append(Message('note_on', note=int(res[1]), time=int(res[2]))) else: track.append( Message('note_off', note=int(res[1]), time=int(res[2]))) #convert back to a format the mdoel can read res[1] = res[1] / 127. res[2] = res[2] / 880. #append the note to the running list of notes ls.append(np.argmax(np.array(listAdd))) #ocasionally add random notes #helps avoid loops if time % 2. <= 0.05: addInd = random.randint(0, len(data[data.shape[0] - 1])) add = data[data.shape[0] - 1][addInd:addInd + 5] # for x in range(5): # add[x] = noteToInd(add[x]) ls += add #ls.append(random.randint(0,dataInd.shape[0])) mid.save(args.save_song_path + 'new_song.mid')
import mido from mido import MidiFile from mido.midifiles import MidiTrack from mido import Message # pattern = MidiFile('Songs/Suteki-Da-Ne.mid') pattern = MidiFile("Songs/twinkle_twinkle.mid") mid = MidiFile() tracks = MidiTrack() tracks.append(tracks) """ for message in pattern: if message.type == 'note_on' or message.type == 'note_off': #print message mid.tracks.append(mid.Message(message.type, note=message.note, velocity=message.velocity, time=message.time)) #elif message.type == 'control_change': # mid.tracks.append(Message(message.type, control=message.control, value=message.value, time=message.time)) #else: # print message # print message.type #tracks.append(Message(message.type, note=message.note, velocity=message.velocity, time=message.time)) #tracks.append(message) """