def label_audio(self): # audio generated by re-interpretting the labels. tmp_path = "/tmp/tmp_mp3.mp3" new_midi = midi_inspect.midiFromLabels(self.labels()) midi.write_midifile(tmp_path, new_midi) os.system("timidity %s" % tmp_path) os.system("rm %s" % tmp_path)
def test_1(): print("[%s:%d] test_1()" % \ (os.path.basename(libs.thisfile()), libs.linenum() ), file=sys.stderr) file = "test.mid" pattern = midi.Pattern(resolution=960) #このパターンがmidiファイルに対応しています。 track = midi.Track() #トラックを作ります pattern.append(track) #パターンに作ったトラックを追加します。 ev = midi.SetTempoEvent(tick=0, bpm=120) #テンポを設定するイベントを作ります track.append(ev) #イベントをトラックに追加します。 e = midi.NoteOnEvent(tick=0, velocity=100, pitch=midi.G_4) #ソの音を鳴らし始めるイベントを作ります。 track.append(e) e = midi.NoteOffEvent(tick=960, velocity=100, pitch=midi.G_4) #ソの音を鳴らし終えるイベントを作ります。 track.append(e) eot = midi.EndOfTrackEvent(tick=1) #トラックを終えるイベントを作ります track.append(eot) midi.write_midifile(file, pattern) #パターンをファイルに書き込みます。
def main(): usage = "%prog [options] <corpus-filename> <out-filename>" description = "Produces a MIDI file from one of the files of the "\ "Kostka-Payne corpus compiled by David Temperley. "\ "<corpus-filename> may be either a path to the file or the "\ "name of a file in the corpus (which is stored within the project)." parser = OptionParser(description=description, usage=usage) options, arguments = parser.parse_args() if len(arguments) < 1: print >>sys.stderr, "You must specify an input filename" sys.exit(1) elif len(arguments) < 2: print >>sys.stderr, "You must specify an output midifile name" sys.exit(1) filename = arguments[0] outname = arguments[1] # Read in the input file seq = DataSequence.from_file(filename) # Produce a midi stream from the data sequence mid = seq.to_midi() # Output the midi file write_midifile(mid, outname)
def matrixToMidi(self, matrix, name="example"): pattern = midi.Pattern() track = midi.Track() pattern.append(track) tickCounter = 0 for i in range(len(matrix)): for j in range(len(matrix[i])): if (matrix[i][j] == 0).any(): if not (matrix[i][j] == 0).all(): #print("Couple found: ") #print(matrix[i][j]) #print("Response: a zero") event = midi.NoteOffEvent(tick=tickCounter, pitch=j + self._lowerBound) track.append(event) tickCounter = 0 #else: #print("Couple found: ") #print(matrix[i][j]) #print("Response: [0, 0]") else: #print("Couple found: ") #print(matrix[i][j]) #print("Response: [1, 1]") velocity = int(matrix[i][j][1]) event = midi.NoteOnEvent(tick=tickCounter, velocity=velocity, pitch=j + self._lowerBound) track.append(event) tickCounter = 0 tickCounter = tickCounter + 1 endOfTrack = midi.EndOfTrackEvent(tick=1) track.append(endOfTrack) #print(pattern) midi.write_midifile("generated/abc{}.mid".format(name), pattern)
def main(): pattern = midi.Pattern() track = midi.Track() pattern.append(track) pitchs = [-5,-5,-6,1,2,3,6,5,3,2,1,1,1,2,1,-7,1,4,-6,1,3,3,2,2,2,3,2,0,2,5,-7,2,3,2,1,1,1,2,1,-7,1,4,-6,1,-6,-6,-5,-5,-5,-5,-6,1,2,3,6,5,3,2,1,1,1,2,1,-7,1,4,-6,1,3,3,2,2,2,3,2,0,2,5,-7,2,3,2,1,1,1,2,1,-7,1,4,-6,1,2,2,1] convert = {0:2, 1:1, 2:3, 3:5, 4:6, 5:8, 6:10, -5:-4, -6:-2, -7:0} pitchs = [convert[x] for x in pitchs] pitchs = [p+60 for p in pitchs] tempos = [2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2,6,2,2,2,2,2,4,2,4,2,2,2] # tempos = [2*x for x in tempos] print(len(pitchs)) print(len(tempos)) # repeats = [4, 3, 6, 3] print('resolution = ', pattern.resolution) idx = 0 hmn = [0] pitchs = [tuple(p+i for i in hmn) for p in pitchs] print(pitchs) for _ in range(100): for ps, t in zip(pitchs, tempos): for p in ps: track_append(track, ON, 0, p) for idx, p in enumerate(ps): track_append(track, OFF, 55*t if idx==0 else 0, p) track_append(track, EOT, tick=1) midi.write_midifile("shoushou.mid", pattern)
def create_midi(text: str, sample_path: str, out_path: str): midifile = midi.read_midifile(sample_path) track = midifile[0][:] target = barcode_to_bin(create_barcode(text, "tmp")) target = [0] * 10 + target pos = 0 for v in target: for i in range(80, 100): on = midi.NoteOnEvent(tick=0, velocity=1, pitch=i if v else 0) track.insert(pos, on) pos += 1 track.insert(pos, midi.NoteOnEvent(tick=40, velocity=1, pitch=0)) pos += 1 for i in range(80, 100): off = midi.NoteOffEvent(tick=0, pitch=i if v else 0) track.insert(pos, off) pos += 1 for i in range(pos, len(track) - 1): track.pop(pos) midifile.append(track) midi.write_midifile(out_path, midifile)
def convertFolder(folderPath, outputName, addDelay): """ Read the ini file and convert the midi file to the standard events """ #read the ini file try: metadata = readIni(os.path.join(folderPath, INI_NAME)) delay = float(metadata["delay"]) / 1000 if "delay" in metadata else 0. if not metadata["pro_drums"] or metadata["pro_drums"] != "True": warnings.warn("song.ini doesn't contain pro_drums = True") except: warnings.warn("song.ini not found") if not addDelay or not delay: delay = 0 # Read the midi file pattern = midi.read_midifile(os.path.join(folderPath, PS_MIDI_NAME)) # clean the midi pattern = cleanMidi(pattern, delay=delay) # Write the resulting file midi.write_midifile(os.path.join(folderPath, outputName), pattern)
def midiExport(self, mainWindowInstance): filename = QtGui.QFileDialog.getSaveFileName(filter="*.mid") try: if filename: with open(filename, "wb") as f: try: outputPattern = midiwrite.Pattern() outputTrack = midiwrite.Track() eventList = [] trackName = "MeeBlip Patch" trackNameEvent = midiwrite.TrackNameEvent(name=trackName) eventList.append(trackNameEvent) for index in (k for k in xrange(48, 80) if k not in range(56, 58) + range(62, 65)): ccEvent = midiwrite.ControlChangeEvent(channel=1) ccEvent.set_control(index) ccEvent.set_value(self.currentPatch.patchCCDict[index]) eventList.append(ccEvent) for event in eventList: outputTrack.append(event) outputPattern.append(outputTrack) midiwrite.write_midifile(f, outputPattern) except IOError as (errno, strerror): QtGui.QMessageBox.warning(mainWindowInstance, "File write error: %s" % errno, "Error writing file %s:\n %s" % (unicode(filename), unicode(strerror))) except: QtGui.QMessageBox.warning(mainWindowInstance, "File write error", "Unknown error writing to file.")
def file_exclude(file_path, instrument_list): '''Delete all the instruments claimed in 'instrument_list' and hold the others in the midi file whose path is 'file_path' ''' if file_path[-4:] != ".mid" and file_path[-4:] != ".MID": print("Invalid midi file!") return else: output_name = file_path[0:-4] + '_processed.mid' pattern = midi.read_midifile(file_path) pattern.make_ticks_abs() exclude_instru = [] try: for i in instrument_list: exclude_instru.append(MIDI_INSTRUMENT.index(i)) except ValueError: print('Please select instrument among: ' + str(MIDI_INSTRUMENT)) return for i in exclude_instru: pattern = delete_track(pattern, instrument=i) pattern.make_ticks_rel() midi.write_midifile(output_name, pattern)
def splitIntoBars(pr1, pr2, pr3): ret = [] ret2 = [] flag = False (r1,c1) = pr1.shape (r2,c2) = pr2.shape (r3,c3) = pr3.shape sizes = [r1, r2, r3] rows = min(sizes) if r1 != r2 or r1 != r3: pr1 = pr1[:rows, :] pr2 = pr2[:rows, :] pr3 = pr3[:rows, :] i = 1 while rows >= i*16: midi.write_midifile("chroma_temp.mid", noteStateMatrixToMidi(pr2[(i)*16-16 : (i)*16,:])) midi_data = pretty_midi.PrettyMIDI('chroma_temp.mid') try: chroma = midi_data.get_chroma(fs=1.0/midi_data.get_end_time()) ret.append([pr1[(i)*16-16 : (i)*16,:], pr2[(i)*16-16 : (i)*16,:], pr3[(i)*16-16 : (i)*16,:]]) ret2.append(chroma) except ZeroDivisionError: flag = True i += 1 return np.asarray(ret), np.asarray(ret2), flag
def sample_midi(states, low=24, high=102, filename='new_music'): scale, last_update = 55, 0 data = midi.Pattern() current = midi.Track() data.append(current) spectrum = high - low states = np.array(states) previous = [0 for i in range(spectrum)] for t, state in enumerate(states + [previous[:]]): off, on = [], [] for i in range(spectrum): n = state[i] p = previous[i] if (p == 1): if (n == 0): off.append(i) elif (n == 1): on.append(i) for note in off: current.append( midi.NoteOffEvent(tick=(t - last_update) * scale, pitch=note + low)) last_update = t for note in on: current.append( midi.NoteOnEvent(tick=(t - last_update) * scale, velocity=40, pitch=note + low)) previous = state end = midi.EndOfTrackEvent(tick=1) current.append(end) midi.write_midifile('{}.mid'.format(filename), data)
def numpy2midi(numpy_path, filename, dur=100, velo=50, inst=1): """ A numpy file that represents tones for a melody gets converted into a midi file :param numpy_path: path of the numpy file :param filename: filename for midi output :param dur: duration of every tone (equidistant) :param velo: velocity of every tone :param inst: instrument (see: https://en.wikipedia.org/wiki/General_MIDI#Program_change_events) """ pattern = midi.Pattern() track = midi.Track() pattern.append(track) data = np.loadtxt(numpy_path, dtype=np.int16) track.append(midi.ProgramChangeEvent(tick=0, channel=0, data=[inst])) # make equidistant tones with fixed velocity for d in data: track.append(midi.NoteOnEvent(tick=0, channel=0, data=[d, velo])) track.append(midi.NoteOffEvent(tick=dur, channel=0, data=[d, velo])) track.append(midi.EndOfTrackEvent(tick=1)) midi.write_midifile(filename + ".mid", pattern)
def record(filename): pattern = midi.Pattern() track = midi.Track() pattern.append(track) port = get_port() try: while True: event = read_event() if event: evtyp = event.name tick = event.tick velocity = event.velocity pitch = event.pitch track.append(event) if port and port.isOpen(): port.write(event) print(evtyp, 'tick:%s' % tick, 'velocity: %s' % velocity, 'pitch: %s' % pitch) finally: eot = midi.EndOfTrackEvent(tick=1) if pattern and track: track.append(eot) if port and port.isOpen(): port.write(eot) port.close() midi.write_midifile(filename, pattern) else: print "S:omething's All F****d Up."
def main(): rootdir = './130000_Pop_Rock_Classical_Videogame_EDM_MIDI_Archive[6_19_15]/Metal_Rock_rock.freemidis.net_MIDIRip/midi/i/iron_maiden/' for subdir, dirs, files in os.walk(rootdir): for file in files: pattern = midi.read_midifile(rootdir + file) bass = midi.Pattern() drum = midi.Pattern() for track in pattern: for event in track: if type(event) == midi.events.TrackNameEvent: trackName = event.text.lower() if trackName.find('bass') != -1: bass.append(track) if trackName.find('drum') != -1: drum.append(track) midi.write_midifile('./bassMIDI/bass_' + file, bass) midi.write_midifile('./drumMIDI/drum_' + file, drum) return
def main(): usage = "%prog [options] <in-file>" description = "Play music using the Harmonical. This allows you to "\ "play music specified precisely in the tonal space. By default, "\ "plays back the input, but can also output to a file." parser = OptionParser(usage=usage, description=description) parser.add_option('-o', '--output', dest="outfile", action="store", help="output the result to a wave file instead of playing back.") parser.add_option('-m', '--midi', dest="midi", action="store_true", help="generate midi data, not audio. Depends on the input format supporting midi file generation.") options, arguments = parse_args_with_config(parser) filename = arguments[0] # Load up the input file infile = HarmonicalInputFile.from_file(filename) if options.midi: midi = infile.render_midi() if options.outfile is not None: # Output a midi file write_midifile(midi, options.outfile) print >>sys.stderr, "Saved midi data to %s" % options.outfile else: print >>sys.stderr, "Playing..." play_stream(midi, block=True) else: print >>sys.stderr, "Generating audio..." audio = infile.render() if options.outfile is not None: # Output to a file instead of playing save_wave_data(audio, options.outfile) print >>sys.stderr, "Saved data to %s" % options.outfile else: print >>sys.stderr, "Playing..." play_audio(audio, wait_for_end=True)
def save(self, path=None): """ Store self at self.path """ if path is not None: self.path = path midi.write_midifile(self.path, self.ptrn)
def noteStateMatrixToMidi(statematrix, name="example", span=span): statematrix = np.array(statematrix) pattern = midi.Pattern() track = midi.Track() pattern.append(track) span = upperBound - lowerBound tickscale = 55 lastcmdtime = 0 prevstate = [0 for x in range(span)] for time, state in enumerate(statematrix + [prevstate[:]]): offNotes = [] onNotes = [] for i in range(span): n = state[i] p = prevstate[i] if p == 1: if n == 0: offNotes.append(i) elif n == 1: onNotes.append(i) for note in offNotes: track.append(midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale, pitch=note + lowerBound)) lastcmdtime = time for note in onNotes: track.append(midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale, velocity=40, pitch=note + lowerBound)) lastcmdtime = time prevstate = state eot = midi.EndOfTrackEvent(tick=1) track.append(eot) midi.write_midifile("{}.mid".format(name), pattern)
def transpose_tone(infile, outfile, bias, change_tempo=False): r""" Transpose the tone of a midi file. If `bias` is negative, it becomes flat. If `bias` is positive, it becomes sharp. Args: infile (str): input midi file outfile (str): output midi file bias (int): the distance the tone shifts. If the bias is too large, and makes some note out of [21, 108], the bias will be modified. change_tempo (bool): if randomly change tempo (by setting resolution) """ pattern = midi.read_midifile(infile) if pattern.format not in (0, 1): raise ValueError( "Pattern format is not 0 or 1. Format 2 is not supported.") m, M = -128, 128 for track in pattern: for evt in track: if isinstance(evt, (midi.NoteOnEvent, midi.NoteOffEvent)): m = max(21 - evt.data[0], m) M = min(108 - evt.data[0], M) bias = min(max(m, bias), M) for track in pattern: for evt in track: if isinstance(evt, (midi.NoteOnEvent, midi.NoteOffEvent)): evt.data[0] += bias if change_tempo: pattern.resolution = math.ceil(2**(np.log2(pattern.resolution) + np.random.rand() * 2) - 1) midi.write_midifile(outfile, pattern)
def notes_to_midi(midi_vals, fn): # Instantiate a MIDI Pattern (contains a list of tracks) pattern = midi.Pattern() pattern.resolution = 480 # Instantiate a MIDI Track (contains a list of MIDI events) track = midi.Track() # Append the track to the pattern pattern.append(track) for val in midi_vals: vel = 0 if val == 0 else 100 # Instantiate a MIDI note on event, append it to the track on = midi.NoteOnEvent(tick=0, velocity=vel, pitch=val) track.append(on) # Instantiate a MIDI note off event, append it to the track (1/16th note = 480/16 = 30 ticks) off = midi.NoteOffEvent(tick=120, pitch=val) track.append(off) # Add the end of track event, append it to the track eot = midi.EndOfTrackEvent(tick=0) track.append(eot) # Print out the pattern print pattern # Save the pattern to disk midi.write_midifile(fn, pattern)
def NoteListToMIDI(filename, note_list, num_aksharam, swaras_per_aksharam): # pattern = midi.read_midifile(filename) MIDI_note_list = [] MIDI_note_list.append(midi.TrackNameEvent(tick = 0, text = 'Rakesh', data = [70, 76, 32, 75, 101, 121, 115, 32, 49])) for i in note_list: if i.MIDINote == 0: event = midi.NoteOnEvent(tick = 0, channel = 0, data = [i.MIDINote, 0]) else: event = midi.NoteOnEvent(tick = 0, channel = 0, data = [i.MIDINote, 100]) MIDI_note_list.append(event) if i.MIDINote == 0: event = midi.NoteOffEvent(tick = int(24*i.NoteLength), channel = 0, data = [i.MIDINote, 0]) else: event = midi.NoteOffEvent(tick = int(24*i.NoteLength), channel = 0, data = [i.MIDINote, 100]) MIDI_note_list.append(event) MIDI_note_list.append(midi.EndOfTrackEvent(tick=0, data = [])) songpattern = midi.Pattern(format = 1, resolution = 96, tracks = \ [midi.Track([midi.SetTempoEvent(tick = 0, data = [12, 53, 0]), midi.TimeSignatureEvent(tick=0, data=[num_aksharam, swaras_per_aksharam/2, 24, 8]), midi.EndOfTrackEvent(tick=0, data = [])]), midi.Track(MIDI_note_list)]) midi.write_midifile(filename, songpattern)
def list_to_midi(chunk_str_list, generated_dir, filename): pattern = midi.Pattern(resolution=480) track = midi.Track() pattern.append(track) for chunk in chunk_str_list: chunk_info = chunk.split("_") event_type = chunk_info[1] if event_type == "no": tick = int(chunk_info[0]) pitch = int(chunk_info[2]) velocity = int(chunk_info[3]) e = midi.NoteOnEvent(tick=tick, channel=0, velocity=velocity, pitch=pitch) track.append(e) elif event_type == "st": tick = int(chunk_info[0]) bpm = int(chunk_info[2]) mpqn = int(chunk_info[3]) ev = midi.SetTempoEvent(tick=tick, bpm=bpm, mpqn=mpqn) track.append(ev) elif event_type == "cc": control = int(chunk_info[3]) value = int(chunk_info[4]) e = midi.ControlChangeEvent(channel=0, control=control, value=value) track.append(e) end_event = midi.EndOfTrackEvent(tick=1) track.append(end_event) midi.write_midifile(generated_dir + filename + '.mid', pattern)
def data_to_song(self, song_name, song_data): """ data_to_song takes a song in internal representation in the shape of [song_length, num_song_features] to a midi pattern all the features are retrieved to the settings in config :param song_data: :return: a midi pattern of song_data """ midi_pattern = midi.Pattern([], resolution=int( self.output_ticks_per_quarter_note)) cur_track = midi.Track([]) cur_track.append( midi.events.SetTempoEvent(tick=0, bpm=self.config.melody_params.bpm)) song_events_absolute_ticks = [] abs_tick_note_beginning = 0 for frame in song_data: ticks = int(round(frame[TICKS_FROM_PREV_START]) ) * 15 + self.config.melody_params.ticks_min if ticks > self.config.melody_params.ticks_max: ticks = self.config.melody_params.ticks_max abs_tick_note_beginning += ticks tick_len = int(round( frame[LENGTH])) * 15 + self.config.melody_params.length_min if tick_len > self.config.melody_params.length_max: tick_len = self.config.melody_params.length_max pitch = int(round( frame[FREQ])) + self.config.melody_params.pitch_min if pitch > self.config.melody_params.pitch_max: pitch = self.config.melody_params.pitch_max velocity = int(round( frame[VELOCITY])) + self.config.melody_params.velocity_min if velocity > self.config.melody_params.velocity_max: velocity = self.config.melody_params.velocity_max song_events_absolute_ticks.append( (abs_tick_note_beginning, midi.events.NoteOnEvent(tick=0, velocity=velocity, pitch=pitch))) song_events_absolute_ticks.append( (abs_tick_note_beginning + tick_len, midi.events.NoteOffEvent(tick=0, velocity=0, pitch=pitch))) song_events_absolute_ticks.sort(key=lambda e: e[0]) abs_tick_note_beginning = 0 for abs_tick, event in song_events_absolute_ticks: rel_tick = abs_tick - abs_tick_note_beginning event.tick = rel_tick cur_track.append(event) abs_tick_note_beginning = abs_tick cur_track.append( midi.EndOfTrackEvent(tick=int(self.output_ticks_per_quarter_note))) midi_pattern.append(cur_track) midi.write_midifile(song_name, midi_pattern)
def main(): pattern = midi.Pattern() track = midi.Track() pattern.append(track) pitchs = [-4,1,3,5,8,6,5,3,3,5,6,5,1,1,5,8,13,15,12,10,8,8,3,5,1,5,8,13,15,12,10,8,8,10,13,13,13,13,8,5,5,5,6,8,3,5,3,5,6,8,3,5,3] pitchs = [p+60 for p in pitchs] tempos = [2,2,2,4,4,2,1,1,2,4,2,2,4,2,2,2,4,4,2,1,1,2,2,10,2,2,2,4,4,2,1,1,1,3,2,1,1,1,2,1,4,2,1,1,1,1,10,2,1,1,1,1,6] tempos = [2*x for x in tempos] print(len(pitchs)) print(len(tempos)) # repeats = [4, 3, 6, 3] print('resolution = ', pattern.resolution) idx = 0 hmn = [0] pitchs = [tuple(p+i for i in hmn) for p in pitchs] print(pitchs) for _ in range(100): for ps, t in zip(pitchs, tempos): for p in ps: track_append(track, ON, 0, p) for idx, p in enumerate(ps): track_append(track, OFF, 55*t if idx==0 else 0, p) track_append(track, EOT, tick=1) midi.write_midifile("qingge.mid", pattern)
def piano_roll_to_midi(piano_roll, filename): """ Saves a midi file from a piano_roll object :param piano_roll: A list of lists, where each sublist represents a time step and contains the midi numbers :param filename: The file name of the output file :return: The midi track that was created """ pattern = midi.Pattern() track = midi.Track() pattern.append(track) offset = 0 for time_step, notes in enumerate(piano_roll): for note in notes: previous_notes = piano_roll[time_step - 1] if time_step > 0 else [] if note not in previous_notes: track.append( midi.NoteOnEvent(tick=offset, velocity=100, pitch=note)) offset = 0 offset += 130 for note in notes: next_notes = piano_roll[ time_step + 1] if time_step < len(piano_roll) - 1 else [] if note not in next_notes: track.append(midi.NoteOffEvent(tick=offset, pitch=note)) offset = 0 eot = midi.EndOfTrackEvent(tick=1) track.append(eot) midi.write_midifile(filename + '.mid', pattern) return track
def handle_drum_track(track, prefix, channel): print "Creating %s*.mid for channel %d" % (prefix, channel) track.make_ticks_abs() drumset = set() drumhash = {} for event in track: event.channel = channel if isinstance(event, midi.NoteOnEvent): drumset.add(event.data[0]) for note in drumset: drumhash[note] = midi.Pattern(resolution=mf.resolution) _track = midi.Track() drumhash[note].append(_track) for event in track: if isinstance(event, midi.NoteEvent): drumhash[event.pitch][0].append(event.copy()) elif not isinstance(event, midi.EndOfTrackEvent): for key in drumhash: drumhash[key][0].append(eval(repr(event))) for key in drumhash: fn = "%s%d.mid" % (prefix, key) drumhash[key].make_ticks_rel() midi.write_midifile(fn, drumhash[key])
def test(): """ Make music! """ initial = get_initial_state() node = get_successor_node(initial) for i in range(220): test_nodes = [] for i in range(1000): test_nodes.append(get_successor_node(node)) node = evaluate(node, test_nodes) pattern = midi.Pattern() pattern.make_ticks_abs() track = midi.Track() pattern.append(track) for note in node.action_path: on = midi.NoteOnEvent(tick=0, velocity=NOTE_VELOCITY, pitch=note) off = midi.NoteOffEvent(tick=NOTE_DURATION[get_rand_duration()], pitch=note) track.append(on) track.append(off) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) print(pattern) midi.write_midifile("example.mid", pattern)
def main(): db = MidiDB(); records = db.records_in_key("C") result_pattern = midi.Pattern(resolution=480) songs = [] for i in range(5): uid = random.choice(records)["id"]; pattern = db.pattern(uid) midiutil.pattern_to_resolution(pattern, 480) track = random.choice(pattern) result_pattern.append(track) songs.append(pattern) remapper = midiremap.MidiRemapper("b0rkestra_description.json", result_pattern) remapper.remap_pattern(result_pattern) midi.write_midifile("test.mid", result_pattern)
def write_to_midi(self, filename): """ Resolution is 220 ticks per quarter note """ pattern = midi.Pattern() track = midi.Track([], False) bass_track = midi.Track([], False) offset = 0 for phrase in self.phrases: for note in phrase.melody: if note.pitch == "rest": offset += 110*note.rhythm else: track.append(midi.NoteOnEvent(tick=offset, velocity=120, pitch=self.tonic_pitch+24+note.pitch)) track.append(midi.NoteOffEvent(tick=(110*note.rhythm), pitch=self.tonic_pitch+24+note.pitch)) offset = 0 for bass_note in phrase.bass_notes: bass_track.append(midi.NoteOnEvent(tick=0, velocity=120, pitch=self.tonic_pitch+bass_note)) bass_track.append(midi.NoteOffEvent(tick=220 * self.beats_per_measure, pitch=self.tonic_pitch+bass_note)) track.append(midi.EndOfTrackEvent(tick=1)) bass_track.append(midi.EndOfTrackEvent(tick=1)) pattern.append(track) pattern.append(bass_track) midi.write_midifile(filename, pattern)
def main(): usage = "%prog [options] <corpus-filename> <out-filename>" description = "Produces a MIDI file from one of the files of the "\ "Kostka-Payne corpus compiled by David Temperley. "\ "<corpus-filename> may be either a path to the file or the "\ "name of a file in the corpus (which is stored within the project)." parser = OptionParser(description=description, usage=usage) options, arguments = parser.parse_args() if len(arguments) < 1: print >> sys.stderr, "You must specify an input filename" sys.exit(1) elif len(arguments) < 2: print >> sys.stderr, "You must specify an output midifile name" sys.exit(1) filename = arguments[0] outname = arguments[1] # Read in the input file seq = DataSequence.from_file(filename) # Produce a midi stream from the data sequence mid = seq.to_midi() # Output the midi file write_midifile(mid, outname)
def hide_message(midi_file, message): print ("Hide message: \"" + message + "\" in " + midi_file) try: # Read midi file tracks = midi.read_midifile(midi_file) # If the midi doesn't have tracks add one if len(tracks) == 0: tracks.append(midi.Track) # Instantiate a MIDI note off event, append it to the track off = midi.NoteOffEvent(tick=0, pitch=midi.G_3) tracks[0].insert(0, off) # Iterate message characters and insert them as program change event for character in message: change_program = midi.ProgramChangeEvent(tick=0, data=[ord(character)]) tracks[0].insert(0, change_program) # Instantiate a MIDI note on event, append it to the track on = midi.NoteOnEvent(tick=0, pitch=midi.G_3) tracks[0].insert(0, on) # Save the pattern to disk midi.write_midifile(midi_file, tracks) except IOError: print ("Error reading the input file")
def store_track_as_file(self, base_path: str): pattern = midi.Pattern() pattern.resolution = self.resolutuion # ticks need to be relative for export self.track.make_ticks_rel() pattern.append(self.track) # create folder if it does not exist folder_path = base_path + self.relative_file_path if not path.exists(folder_path): os.makedirs(folder_path) # build filename if self.is_drum: export_filename = self.file_name[:-4] + "-" + str( self.file_id) + "-drum.mid" else: export_filename = self.file_name[:-4] + "-" + str( self.file_id ) + "-" + self.category.name + "-" + self.instrument.name + ".mid" midi.write_midifile(midifile=folder_path + export_filename, pattern=pattern)
def main(): composerName = "mozart" createNewTransition = False inputFiles = glob.glob('midis/midiworld/classic/' + composerName + '*.mid') if createNewTransition: getTransitionMatrix(inputFiles, composerName) lengthM = loadMatrixFromFile("matrices/" + composerName + "LengthM.dat") pitchM = loadMatrixFromFile("matrices/" + composerName + "PitchM.dat") velocityM = loadMatrixFromFile("matrices/" + composerName + "VelocityM.dat") notesList = highestPlausibility(lengthM, pitchM, velocityM) outFileName = "midis/" + composerName + "New.mid" # Instantiate a MIDI Pattern (contains a list of tracks) resolution = 384 pattern = midi.Pattern(resolution=resolution) # Instantiate a MIDI Track (contains a list of MIDI events) track = midi.Track() # Append the track to the pattern pattern.append(track) # Set Instrument to piano pEvent = midi.ProgramChangeEvent(tick=0, channel=0) pEvent.set_value(1) track.append(pEvent) # Set tempo to 150 bpm tEvent = midi.SetTempoEvent(tick=0) tEvent.set_bpm(150) track.append(tEvent) for note in notesList: tick = Note.lengthToTick(note.length, resolution) pitch = note.pitch velocity = note.volume # Append the new note track.append( midi.NoteOnEvent(channel=0, tick=0, pitch=pitch, velocity=velocity)) # Stop the previous note to avoid unpleasant mixing track.append( midi.NoteOnEvent(channel=0, tick=tick, pitch=pitch, velocity=0)) # Add the end of track event, append it to the track eot = midi.EndOfTrackEvent(tick=0) track.append(eot) print pattern # Save the pattern to disk midi.write_midifile(outFileName, pattern) print "\nMusic written to " + outFileName + "\n"
def main(argc, argv): if argc != 3: print("Usage: python csv2midi.py <csv file> <output file name>") exit(1) # Pattern is the midi file. It can contain multiple tracks, # but we are using just one. pattern = midi.Pattern() track = midi.Track() pattern.append(track) print(argv[1]) csvfile = open(argv[1], 'rb') counter = 0 for row in csvfile: print(counter) vals = [x.strip() for x in row.split(',')] print(vals) vals = filter(None, vals) vals = map(lambda x: int(x), vals) tick = vals[0] base = vals[1] + 60 print(len(vals)) offsets = vals[2:] for i in range(0, len(offsets)): offsets[i] = int(offsets[i]) + base #print tick #print base #print offsets data = [] track.append(midi.NoteOnEvent(tick=12, channel=1, data=[base] + [110])) for x in offsets: track.append(midi.NoteOnEvent(tick=0, channel=1, data=[x]+[110])) track.append(midi.NoteOffEvent(tick=tick, channel=1, data=[base] + [0])) for x in offsets: track.append(midi.NoteOffEvent(tick=0, channel=1, data=[x]+[0])) counter += 10 # End of track appears 1 tick after last event track.append(midi.EndOfTrackEvent(tick=1)) print("###########################################") print("ORIGINAL") print("###########################################") #pattern2 = midi.read_midifile("vexation.mid") #print(pattern2) #print("###########################################") #print("RECOVERED") #print("###########################################") #print pattern midi.write_midifile(argv[2], pattern)
def noteStateMatrixToMidi(statematrix, name="example", span=span): """ Transforms a matrix representation of notes and into a midi file. :param statematrix: matrix representation of song :param name: name for midi file :param span: pitch range, default span (78) :type statematrix: numpy array :type name: str :type span: int :returns: None :rtype: None """ statematrix = np.array(statematrix) if not len(statematrix.shape) == 3: statematrix = np.dstack((statematrix[:, :span], statematrix[:, span:-2])) statematrix = np.asarray(statematrix) pattern = midi.Pattern() track = midi.Track() pattern.append(track) span = upperBound - lowerBound tickscale = 55 lastcmdtime = 0 prevstate = [[0, 0] for x in range(span)] for time, state in enumerate(statematrix + [prevstate[:]]): offNotes = [] onNotes = [] for i in range(span): n = state[i] p = prevstate[i] if p[0] == 1: if n[0] == 0: offNotes.append(i) elif n[1] == 1: offNotes.append(i) onNotes.append(i) elif n[0] == 1: onNotes.append(i) for note in offNotes: track.append( midi.NoteOffEvent(tick=(time - lastcmdtime) * tickscale, pitch=note + lowerBound)) lastcmdtime = time for note in onNotes: track.append( midi.NoteOnEvent(tick=(time - lastcmdtime) * tickscale, velocity=120, pitch=note + lowerBound)) lastcmdtime = time prevstate = state eot = midi.EndOfTrackEvent(tick=1) track.append(eot) midi.write_midifile("{}.mid".format(name), pattern)
def on_frame(self, controller): # Get the most recent frame and report some basic information frame = controller.frame() previous_frame = controller.frame(1) last_frame = controller.frame(10) back_frame = controller.frame(20) #print "Frame id: %d, timestamp: %d, hands: %d, fingers: %d, tools: %d, gestures: %d" % ( # frame.id, frame.timestamp, len(frame.hands), len(frame.fingers), len(frame.tools), len(frame.gestures())) # direction of index finger direction_1 = frame.hands.rightmost.fingers[1].bone(2).direction direction_2 = last_frame.hands.rightmost.fingers[1].bone(2).direction direction_3 = back_frame.hands.rightmost.fingers[1].bone(2).direction middle_1 = frame.hands.rightmost.fingers[2].bone(2).direction middle_2 = last_frame.hands.rightmost.fingers[2].bone(2).direction middle_3 = back_frame.hands.rightmost.fingers[2].bone(2).direction # angle of these two finger vector if (direction_1).angle_to(direction_2) > np.pi / 9 and ( direction_1).angle_to(direction_3) < np.pi / 15: print "index finger press action, direction vector: ", direction_1, direction_2, direction_3 # tick of midi is milli second 1e-3second, timestamp of frame is micro second 1e-6second #start_ = int((frame.timestamp - self.first_timestamp)/ 1000.0) self.track.append( midi.NoteOnEvent(tick=50, velocity=50, pitch=midi.G_3)) self.track.append( midi.NoteOffEvent(tick=150, velocity=50, pitch=midi.G_3)) if (middle_1).angle_to(middle_2) > np.pi / 10 and ( middle_1).angle_to(middle_3) < np.pi / 15: print "index finger press action, direction vector: ", middle_1, middle_2, middle_3 # tick of midi is milli second 1e-3second, timestamp of frame is micro second 1e-6second #start_ = int((frame.timestamp - self.first_timestamp)/ 1000.0) self.track.append( midi.NoteOnEvent(tick=50, velocity=50, pitch=midi.A_3)) self.track.append( midi.NoteOffEvent(tick=150, velocity=50, pitch=midi.A_3)) # get the normal vector of the palm normal = frame.hands.rightmost.palm_normal previous_normal = previous_frame.hands.rightmost.palm_normal print normal[0], normal[1], normal[2] # stop is the palm normal is inversed if previous_normal[2] * normal[2] < 0: # end the track, add it to the pattern print "end track event, track adds to pattern" self.track.append(midi.EndOfTrackEvent(tick=1)) self.pattern.append(self.track) # write pattern to file midi print "write pattern to file: " midi.write_midifile("example.mid", self.pattern) # stop the listener print "stop" controller.remove_listener(self)
def three_track_midi(source, dest, tr1, tr2, tr3): if isinstance(mf, str): mf = midi.read_midifile(mf) pat = midi.Pattern() pat.append(mf[tr1]) pat.append(mf[tr2]) pat.append(mf[tr3]) midi.write_midifile(dest, pat)
def write(self): eot = midi.EndOfTrackEvent() eot.tick = self.delta_tick() self.track.append(eot) meta_track = self.make_meta_track() pattern = midi.Pattern(tracks = [meta_track, self.track], resolution = math.ceil(self.subres * self.subdivision / 4.0)) midi.write_midifile(self.filename, pattern)
def render(self): # Add the end of track event, append it to the track eot = midi.EndOfTrackEvent(tick=1) self.track.append(eot) # Print out the pattern print self.pattern # Save the pattern to disk midi.write_midifile("example.mid", self.pattern)
def change_midi_speed(input_file, output_file, tmpo): pattern = midi.read_midifile(input_file) for track in pattern: for event in track: if type(event) is midi.SetTempoEvent: event.set_bpm(float(tmpo)) break midi.write_midifile(output_file, pattern)
def main(): composerName = "mozart" createNewTransition = False inputFiles = glob.glob('midis/midiworld/classic/' + composerName + '*.mid') if createNewTransition: getTransitionMatrix(inputFiles, composerName) lengthM = loadMatrixFromFile("matrices/" + composerName + "LengthM.dat") pitchM = loadMatrixFromFile("matrices/" + composerName + "PitchM.dat") velocityM = loadMatrixFromFile("matrices/" + composerName + "VelocityM.dat") notesList = highestPlausibility(lengthM, pitchM, velocityM) outFileName = "midis/" + composerName + "New.mid" # Instantiate a MIDI Pattern (contains a list of tracks) resolution=384 pattern = midi.Pattern(resolution=resolution) # Instantiate a MIDI Track (contains a list of MIDI events) track = midi.Track() # Append the track to the pattern pattern.append(track) # Set Instrument to piano pEvent = midi.ProgramChangeEvent(tick=0, channel=0) pEvent.set_value(1) track.append(pEvent) # Set tempo to 150 bpm tEvent = midi.SetTempoEvent(tick=0) tEvent.set_bpm(150) track.append(tEvent) for note in notesList: tick = Note.lengthToTick(note.length, resolution) pitch = note.pitch velocity = note.volume # Append the new note track.append(midi.NoteOnEvent(channel=0, tick=0, pitch = pitch, velocity=velocity)) # Stop the previous note to avoid unpleasant mixing track.append(midi.NoteOnEvent(channel=0, tick=tick, pitch=pitch,velocity=0)) # Add the end of track event, append it to the track eot = midi.EndOfTrackEvent(tick=0) track.append(eot) print pattern # Save the pattern to disk midi.write_midifile(outFileName, pattern) print "\nMusic written to " + outFileName + "\n"
def main(): usage = "%prog [options] <input-midi> <output-filename>" description = "Cleans up a midi file by getting rid of a load of "\ "stuff that makes the music sound good, but isn't needed "\ "by our algorithms. See options for details." parser = OptionParser(usage=usage, description=description) parser.add_option('-d', '--remove-drums', dest="remove_drums", action="store_true", help="filter out drum tracks", default=False) parser.add_option('-p', '--pc', '--remove-program-change', dest="remove_pc", action="store_true", help="filter out all program change (instrument) events", default=False) parser.add_option('-x', '--remove-text', '--txt', dest="remove_text", action="store_true", help="filter out all text events of any type", default=False) parser.add_option('-o', '--one-track', dest="one_track", action="store_true", help="reduce everything down to one track", default=False) parser.add_option('-t', '--remove-tempo', dest="remove_tempo", action="store_true", help="remove all tempo events", default=False) parser.add_option('-c', '--remove-control', dest="remove_control", action="store_true", help="remove all control change events", default=False) parser.add_option('--ch', '--one-channel', dest="one_channel", action="store_true", help="use only one channel: every event occurs on channel 0", default=False) parser.add_option('--mc', '--remove-misc-control', dest="remove_misc_control", action="store_true", help="filter out a whole load of device control events: aftertouch, channel aftertouch, pitch wheel, sysex, port", default=False) parser.add_option('--rno', '--real-note-offs', dest="real_note_offs", action="store_true", help="replace 0-velocity note-ons with actual note-offs. Some midi files use one, some the other", default=False) parser.add_option('--remove-duplicates', dest="remove_duplicates", action="store_true", help="tidy up at the end to remove any duplicate notes", default=False) parser.add_option('-i', '--invert', dest="invert", action="store_true", help="inverts all options. I.e. applies all filters except those selected by the above options", default=False) parser.add_option('-r', '--remove-channels', dest="remove_channels", action="append", type="int", help="filter out all events of the numbered channel. Use multiple options to filter multiple channels at once") parser.add_option('--resolution', '--res', dest="resolution", action="store", type="int", help="change the resolution of the midi data from that read in from the file to that given") options, arguments = parse_args_with_config(parser) if len(arguments) < 2: print >>sys.stderr, "You must specify an input and output filename" sys.exit(1) in_filename = os.path.abspath(arguments[0]) out_filename = os.path.abspath(arguments[1]) # Read in the midi file mid = read_midifile(in_filename, force_resolution=options.resolution) # Build a dictionary of kwargs to select what operations to apply filters = { 'remove_drums' : options.remove_drums ^ options.invert, 'remove_pc' : options.remove_pc ^ options.invert, 'remove_all_text' : options.remove_text ^ options.invert, 'one_track' : options.one_track ^ options.invert, 'remove_tempo' : options.remove_tempo ^ options.invert, 'remove_control' : options.remove_control ^ options.invert, 'one_channel' : options.one_channel ^ options.invert, 'remove_misc_control' : options.remove_misc_control ^ options.invert, 'real_note_offs' : options.real_note_offs ^ options.invert, } print "Filters to be applied:" if options.remove_channels is not None: print " removing channels: %s" % ", ".join(str(ch) for ch in options.remove_channels) if options.resolution is not None: print " changing resolution to %d" % options.resolution print "\n".join(" %s" % name for (name,val) in filters.items() if val) filters['remove_duplicates'] = options.remove_duplicates print "Filtering..." # Apply channel filters first if options.remove_channels is not None: remove_channels(mid, options.remove_channels) filtered = simplify(mid, **filters) print "Midi output to",out_filename write_midifile(filtered, out_filename)
def sequence_to_midi(state_matrix, filepath, meta_info=None): """ Converts a state_matrix to the corresponding 'pattern' and writes the pattern as a midi file. :param state_matrix: The state matrix. :type state_matrix: 2-D list :param filepath: The path of the output midi file. :type filepath: str :param meta_info: Resolution and tempo-event of the pattern. :type meta_info: (int, SetTempoEvent or None) or None :returns: The pattern sequence corresponding to the state matrix. :return_type: list """ resolution, tempo_event = meta_info if meta_info else None pattern = midi.Pattern(resolution=resolution) track = midi.Track() pattern.append(track) if tempo_event: track.append(tempo_event) # Append the very first tick (which will only have NoteOn events) notes_on, _ = state_diff([0] * 128, state_matrix[0]) for note in notes_on: track.append(midi.NoteOnEvent(tick=0, channel=0, data=note)) # Append the rest of the ticks current_state_index = 0 while current_state_index < len(state_matrix): next_state_index = get_next_different_state( state_matrix, current_state_index) ticks_elapsed = next_state_index - current_state_index current_state = state_matrix[current_state_index] next_state = state_matrix[next_state_index] if next_state_index < len( state_matrix) else [0] * 128 notes_on, notes_off = state_diff(current_state, next_state) for note in notes_on: track.append(midi.NoteOnEvent( tick=ticks_elapsed, channel=0, data=note)) # The rest of the events are happening simultaneously, # so set time_elapsed (tick) = 0 for them ticks_elapsed = 0 for note in notes_off: track.append(midi.NoteOffEvent( tick=ticks_elapsed, channel=0, data=note)) ticks_elapsed = 0 current_state_index = next_state_index track.append(midi.EndOfTrackEvent(tick=1)) midi.write_midifile(filepath, pattern) return pattern
def writeDebugTrack(track, filename, index): if not os.path.exists(tracks_dir): os.makedirs(tracks_dir) pattern = midi.Pattern() pattern.append(track) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) #print "Writing debug track for "+filename+". Track #"+str(index) #print pattern midi.write_midifile(tracks_dir + "/" + filename + "_track"+str(index), pattern)
def write(self, outfile): """ Renders MIDI data and writes it out the the given file. @type outfile: string or open file @param outfile: filename to write to or an open file(-like) object """ mid = self.render() write_midifile(mid, outfile)
def midiMap(attr,f_name): pattern = midi.Pattern() track = midi.Track() pattern.append(track) file_name = f_name print 'length = '+str(len(attr)) for k in range(len(attr['key'])): # Instantiate a MIDI note on event, append it to the track #print "midi."+str(attr['key'][k])+"_"+str(attr['octave'][k]) key = attr['key'][k] #print key octave = attr['octave'][k] #print key_names[key] key_number = key_names[key] + 12*(octave-1) #print key_number #pitch = eval("midi."+str(key)+"_"+str(octave)) pitch = key_number #print pitch ed = attr['effective_duration'][k] * 500 if k==(len(attr['key'])-1): timing_f = 50*ed timing_i = 0 else : timing_f = attr['times'][k+1] * 1000 timing_i = attr['times'][k] * 1000 #print timing_f - timing_i #print "ed = " +str(ed) on = midi.NoteOnEvent(tick=0, velocity=70, pitch=pitch) track.append(on) off = midi.NoteOffEvent(tick=int(timing_f - timing_i - ed) , pitch=pitch) track.append(off) on = midi.NoteOnEvent(tick=1, velocity=0, pitch=pitch) track.append(on) off = midi.NoteOffEvent(tick=1, pitch=pitch) track.append(off) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) #print pattern file_name = os.path.basename(file_name).split('.')[0] print(file_name) path = "recorded_to_midi/" + file_name + ".mid" midi.write_midifile(path, pattern)
def load_stream(self, stream): """ Loads the whole of an L{EventStream<midi.EventStream>}. Call L{play} to start playback. """ temp_file = TemporaryFile(suffix=".mid") write_midifile(stream, temp_file) temp_file.seek(0) mixer.music.load(temp_file) self._music_loaded = True
def musicToMidi(filename, music): """ musicToMidi takes a filename (which must end in ".mid") and a music structure and writes a MIDI file. :param filename: :param music: :return: """ checkMidiCompatible(music) # are the volumes and pitches within 0-127? e = musicToMEvents(music) # convert to MEvents p = mEventsToPattern(e) # convert to a pythonmidi Pattern midi.write_midifile(filename, p) # write the MIDI file
def write_file(name, results): """ Takes a list of all notes generated per track and writes it to file """ results = zip(*list(results)) for i, result in enumerate(results): fpath = os.path.join(SAMPLES_DIR, name + '_' + str(i) + '.mid') print('Writing file', fpath) os.makedirs(os.path.dirname(fpath), exist_ok=True) mf = midi_encode(unclamp_midi(result)) midi.write_midifile(fpath, mf)
def main(): usage = "%prog [options] <seq-file>:<index> <midi-file> <midi-out>" description = "Aligns a chord sequence with a MIDI file and inserts "\ "marker events into the MIDI data to mark where chord changes "\ "are. Alignment parameters will be loaded from a file (not "\ "implemented yet), but can be overridden using the script's "\ "options." parser = OptionParser(usage=usage, description=description) parser.add_option("--mbpb", "--midi-beats-per-beat", dest="beats_per_beat", type="int", help="number of midi beats to align with a single sequence beat (see SequenceMidiAlignment.midi_beats_per_beat)") parser.add_option("--ss", "--sequence-start", dest="sequence_start", type="int", help="number of midi ticks after the first note-on event when the chord sequence begins (see SequenceMidiAlignment.sequence_start)") parser.add_option("--repeats", dest="repeats", help="repeat spans, in the form 'start_chord,end_chord,count', separated by semicolons (see SequenceMidiAlignment.repeat_spans)") parser.add_option("--lyrics", dest="lyrics", action="store_true", help="use lyrics events instead of marker events to mark the chords") options, arguments = parser.parse_args() if len(arguments) < 3: print "You must specify a sequence file, midi file and output midi filename" sys.exit(1) # Get the chord sequence filename,__,index = arguments[0].partition(":") index = int(index) seq = SequenceIndex.from_file(filename).sequence_by_index(index) # Load the input midi data mid = read_midifile(arguments[1]) outfile = arguments[2] # For now, just create a new default alignment # TODO: load the alignment parameters from a file or from the # sequence data itself alignment = SequenceMidiAlignment() # Override alignment parameters if options are given if options.beats_per_beat is not None: alignment.midi_beats_per_beat = options.beats_per_beat if options.sequence_start is not None: alignment.sequence_start = options.sequence_start if options.repeats is not None: repeats = [] try: for string_triple in options.repeats.split(":"): start,end,count = string_triple.split(",") start,end,count = int(start), int(end), int(count) repeats.append((start,end,count)) except: print "Error parsing repeat spans:" raise alignment.repeat_spans = repeats alignment.align(seq, mid, lyrics=options.lyrics) write_midifile(mid, outfile)
def save_tracks(original_filename, new_filename, track_list): """ Save the tracks to disk as a .mid file. """ pattern = midi.read_midifile(filename) for track in pattern: if track not in track_list: for event in track: try: event.velocity = 1 except AttributeError: pass midi.write_midifile(new_filename, pattern)
def generate_output(self): TEMPO = int(Start.kwargs.get('tempo', 60)) OUTPUT = Start.kwargs.get('out', 'out.mid') t = midi.new_stream(resolution=120, tempo=TEMPO) for i, inp in enumerate(self.input.values()): for j, item in enumerate(inp): if isinstance(item, Chord): pitches = [ p + 60 for p in item.pitch_classes ] # XXX else: raise TypeError('Only chords supported for MIDI out right now') for pitch in pitches: noteon(t, i, pitch, j * 120, 100, 100) midi.write_midifile(t, OUTPUT)
def main(): filename, basename, _ = filebaseext( argv[ 1 ] ) tick_per_quantum = int( argv[ 2 ] ) original = midi.read_midifile( filename ) qstats, qtrack = quantize( original[ 0 ], tick_per_quantum ) midi.write_midifile( '{}.q{}.mid'.format( basename, tick_per_quantum ), midi.Pattern( format = 0, resolution = original.resolution, tracks = [ qtrack ] ) ) print 'qstats:' for delta, count in qstats: print '\ttick {}: # {}'.format( delta, count )
def output_midi_simple_array(notesmatrix, midipath, tickscale = 55): notesmatrix = numpy.asarray(notesmatrix) pattern = midi.Pattern() track = midi.Track() pattern.append(track) lowerNote = 52 e = midi.ProgramChangeEvent() e.value = 80 track.append(e) fillTrack(track, notesmatrix, lowerNote, tickscale) midi.write_midifile("{}".format(midipath), pattern)
def test_mary(self): midi.write_midifile("mary.mid", mary_test.MARY_MIDI) pattern1 = midi.read_midifile("mary.mid") midi.write_midifile("mary.mid", pattern1) pattern2 = midi.read_midifile("mary.mid") self.assertEqual(len(pattern1), len(pattern2)) for track_idx in range(len(pattern1)): self.assertEqual(len(pattern1[track_idx]), len(pattern2[track_idx])) for event_idx in range(len(pattern1[track_idx])): event1 = pattern1[track_idx][event_idx] event2 = pattern1[track_idx][event_idx] self.assertEqual(event1.tick, event2.tick) self.assertEqual(event1.data, event2.data)
def createExampleMidi(notes): print "printing MIDI" pattern = midi.Pattern() track = midi.Track() pattern.append(track) on = midi.NoteOnEvent(tick=0, velocity=100, pitch=midi.G_3) track.append(on) off = midi.NoteOffEvent(tick=100000, pitch=midi.G_3) track.append(off) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) print pattern midi.write_midifile("example.mid", pattern)
def main(argv): if len(argv) < 4: print "usage: pickled copy_deets_from out_file" return pickled, copy_deets_from, out_file = argv[1:4] with open(pickled) as f: evs = pickle.load(f) deets_mid = midi.read_midifile(copy_deets_from) track, last_t = gen_track(deets_mid, evs) gen_mid = midi.Pattern() gen_mid.append(gen_tempo_track(deets_mid, last_t)) gen_mid.append(track) midi.write_midifile(out_file, gen_mid)
def decompose_midi(fname, out_dir=None): """takes fname and decomposes its tracks into multiple midi files in out_dir grouped by families found here https://www.midi.org/specifications/item/gm-level-1-sound-set""" # load pattern as midi pattern = midi.read_midifile(fname) # list of names corresponding to following pc ranges family_names = ["piano", "chrom_percus", "organ", "guitar", "bass", "strings", "ensemble", "brass", "reed", "pipe", "synth_lead", "synth_pad", "synth_effects", "ethnic", "percussive", "sound_effects", "drums"] # constant ranges found in spec for instrument family grouping family_ranges = [range(0,8), range(8,16), range(16,24), range(24,32), range(32,40), range(40,48), range(48, 56), range(56,64), range(65,72), range(72,80), range(80, 88), range(88, 96), range(96,104), range(104,112), range(112, 120), range(120,128)] # create a list of lists to store tracks corresponding to each family grouped_tracks = [[] for x in family_ranges] for curr_family in range(len(family_ranges)): for track in pattern: track_done = False for event in track: # Channel 10 (0 indexed is 9) is only drums if "ProgramChangeEvent" in repr(event) and int(event.channel) != 9: if int(event.data[0]) in family_ranges[curr_family]: grouped_tracks[curr_family].append(track) track_done = True # print "Adding track titled {} to family {}".format(track[0].text, family_names[curr_family]) if track_done: continue # handle drums specially drums = [] for track in pattern: track_done = False for event in track: # Channel 10 (0 indexed is 9) is drums if "ProgramChangeEvent" in repr(event): if int(event.channel) == 9 : drums.append(track) track_done = True print "Adding track titled {} to family {}".format(track[0].text, family_names[-1]) grouped_tracks.append(drums) fname_pre = fname.split(".")[0] for curr_family in range(len(family_names)): if grouped_tracks[curr_family] != []: out = midi.Pattern(format=pattern.format, resolution=pattern.resolution, tracks=grouped_tracks[curr_family]) if out_dir is None: midi.write_midifile("{}_{}.mid".format(fname_pre, family_names[curr_family]), out) else: midi.write_midifile("{}_{}.mid".format(fname_pre, family_names[curr_family]), out)
def main(): #pattern1 = midi.read_midifile("midi/5RAP_04.MID") bars = [] pattern = midi.read_midifile("midi/5RAP_04.MID") #pattern = midi.read_midifile("midi/decoy.mid") #pattern = midi.read_midifile("midi/drum_patterns.mid") #print_events(pattern, []) pattern = sanitize(pattern) midi.write_midifile("test.mid", pattern) pattern = midi.read_midifile("test.mid") print pattern return
def decompose_by_channel(fname, out_dir=None): # load pattern as midi pattern = midi.read_midifile(fname) # list of names corresponding to following pc ranges family_names = ["piano", "chrom_percus", "organ", "guitar", "bass", "strings", "ensemble", "brass", "reed", "pipe", "synth_lead", "synth_pad", "synth_effects", "ethnic", "percussive", "sound_effects", "drums"] # constant ranges found in spec for instrument family grouping family_ranges = [range(0,8), range(8,16), range(16,24), range(24,32), range(32,40), range(40,48), range(48, 56), range(56,64), range(65,72), range(72,80), range(80, 88), range(88, 96), range(96,104), range(104,112), range(112, 120), range(120,128)] # create a list of lists to store tracks corresponding to each family grouped_tracks = [[] for x in family_ranges] channel_tracks = [midi.Track() for x in range(16)] track_has_content = [False for x in range(16)] # maps channels to instrument codes # channel_map = {} # make a track of all events that are not note on/note off events non_note_events = midi.Track() for track in pattern: for event in track: if "NoteOnEvent" not in repr(event) and "NoteOffEvent" not in repr(event): non_note_events.append(event) for t in channel_tracks: t.append(event) else: for i in range(len(channel_tracks)): if i == int(event.channel): channel_tracks[i].append(event) else: channel_tracks[i].append(midi.NoteOnEvent(tick=event.tick, velocity=0, pitch=midi.G_3)) if "ProgramChangeEvent" in repr(event) and int(event.channel) != 9: for curr_family in range(len(family_ranges)): if int(event.data[0]) in family_ranges[curr_family]: grouped_tracks[curr_family].append(channel_tracks[int(event.channel)]) break # channel_map[int(event.channel)] = int(event.data[0]) grouped_tracks.append([channel_tracks[9]]) fname_pre = fname.split(".")[0] for curr_family in range(len(grouped_tracks)): if grouped_tracks[curr_family] != []: out = midi.Pattern(format=pattern.format, resolution=pattern.resolution, tracks=(grouped_tracks[curr_family])) if out_dir is None: midi.write_midifile("{}_{}.mid".format(fname_pre, family_names[curr_family]), out) else: midi.write_midifile("{}_{}.mid".format(fname_pre, family_names[curr_family]), out)