def writeToMidi(): filename = 'beat.mid' MyMIDI = MIDIFile(2) MyMIDI.addTempo(track, timer, bpm) MyMIDI.addTimeSignature(track, timer, int(measure[0]), int(math.log(int(measure[1]), 2)), 24) pos = 0 for ts in timestampKick: MyMIDI.addNote(track, channel, 36, 2 * ts, rhythmKick[pos], velocity) pos += 1 pos = 0 for ts in timestampSnare: MyMIDI.addNote(track, channel, 39, 2 * ts, rhythmSnare[pos], velocity) pos += 1 pos = 0 for ts in timestampHat: MyMIDI.addNote(track, channel, 42, 2 * ts, rhythmHat[pos], velocity) pos += 1 with open(filename, 'wb') as output_file: MyMIDI.writeFile(output_file) print('Successfully exported the rhythm as: ' + str(filename))
def writeToMidi(): filename = 'beat.mid' MyMIDI = MIDIFile(2) #Om welk midifile het gaat MyMIDI.addTempo(track,timer,bpm) #Om het tempo in te stellen MyMIDI.addTimeSignature(track,timer,int(measure[0]),int(math.log(int(measure[1]),2)),24) #Timesignature heeft een track nummer nodig(0), een tijdplek (timer) om aan te geven waar de midi start (begint nu vanaf miditick 1), #Daarnaast het aantal tellen in een maat (nu kan de user opgeven, maar bijvoorbeeld 4), de waarde van een tel uitgedrukt in een exponent(dus 3 = #2^3= 8ste noot enz., en daarnaast het aantal clocks per tick. 24 in een kwartnoot. pos = 0 for ts in rhythmKick: MyMIDI.addNote(track,channel,36,ts,0.25,velocity) #Voeg een noot toe door de track, het midikanaal, nootnummer, de starttijd (dus de positie in het grid (2 keer de timestamp waarde)), nootlengte in ms en de velocity pos+=1 pos = 0 for ts in rhythmSnare: MyMIDI.addNote(track,channel,39,ts,0.25,velocity) pos+=1 pos = 0 for ts in rhythmHat: MyMIDI.addNote(track,channel,42,ts,0.25,velocity) pos+=1 with open(filename, 'wb') as output_file: MyMIDI.writeFile(output_file) #Schrijf het bestand uit print('Successfully exported the rhythm as: ' + str(filename)) #Gwn een leuk print ding
def to_midi_file(self, file): midi = MIDIFile(1) midi.addTempo(0, 0, self.tempo) midi.addTimeSignature(0, 0, self.time_signature[0], int(np.sqrt(self.time_signature[1])), 24) if self.key.scale == Scale.MAJOR: mode = midiutil.MAJOR else: mode = midiutil.MINOR if self.key.get_circle_of_fifths()[1] == 'Sharps': accidental_type = midiutil.SHARPS else: accidental_type = midiutil.FLATS midi.addKeySignature(0, 0, self.key.get_circle_of_fifths()[0], accidental_type, mode) for note in self.notes: midi.addNote(0, 0, note.pitch.midi_number, note.duration.start_beat * 4, note.duration.total_beat * 4, utils.MIDI_VOLUME) with open(file, "wb") as output_file: midi.writeFile(output_file)
class MidiExport: global midiExportFile midinote_l = 36 midinote_m = 38 midinote_h = 42 midinote_ho = 46 def __init__(self, generator): self.midiExportFile = MIDIFile(2) # (track, time, tempo) self.midiExportFile.addTempo(1000, 0, bpm) numerator = generator.beatPerMeasure denominator = int(math.log(generator.beatUnit, 2)) clocksPerTick = int(24 * (4 / generator.beatUnit)) self.midiExportFile.addTimeSignature(1000, 0, numerator, denominator, clocksPerTick) def export(self, sequence, filename): sixteenthNoteDuration = (60. / bpm) * .25 for event in sequence: if (len(event) > 2): for sound in event[2:]: if sound is "l": pitch = self.midinote_l amp = 110 if event[1] == 0 else 80 elif sound is "m": pitch = self.midinote_m amp = 110 if event[1] == 0 else 80 elif sound is "h": pitch = self.midinote_h amp = 80 # (track, channel, pitch, time, duration, volume) self.midiExportFile.addNote(0, 9, pitch, event[0] * .25, .25, amp) with open(filename + ".mid", "wb") as output_file: self.midiExportFile.writeFile(output_file)
def make_midi(tbon, outfile, firstbar=0, quiet=False, metronome=0): """ Parse and evaluate the source string. Write the output to the specified outfile name. kwargs: transpose -- Number of semitones to transpose the output. May be positive or negative. volume -- MIDI track volume track -- Midi file track number channel -- MIDI channel number octave -- Initial MIDI octave number (0 - 10) numeric -- tbon notation can be either named pitches (cdefgab) or numbers (1234567) with 1 corresponding to 'c'. """ parts = tbon.output numparts = len(parts) print("Found {} parts".format(numparts)) metronotes = tbon.metronome_output if metronome == 0: numTracks = numparts elif metronome == 1: numTracks = 1 else: numTracks = 1 + numparts meta = tbon.meta_output beat_map = tbon.beat_map MyMIDI = MIDIFile(numTracks, adjust_origin=True, removeDuplicates=False, deinterleave=False) #MyMIDI.addTempo(track, 0, tempo) trk0 = 0 for m in meta: if m[0] == 'T': MyMIDI.addTempo(trk0, m[1], m[2]) elif m[0] == 'K' and metronome != 1: time = m[1] sf, mi = m[2] track = m[3] mode = MINOR if mi == 1 else MAJOR accidentals = abs(sf) acc_type = SHARPS if sf > 0 else FLATS #print("Inserting key signature at time {}".format(time)) #print(accidentals, acc_type, mode) MyMIDI.addKeySignature(track, time, accidentals, acc_type, mode) elif m[0] == 'M': ## Time signature time = m[1] numerator = m[2] denominator = m[3] track = m[4] ## midi denominator specified a power of 2 midi_denom = {2: 1, 4: 2, 8: 3, 16: 4}[denominator] ## We want to make the midi metronome match beat duration. ## This requires recognizing compound meters ## See http://midiutil.readthedocs.io/en/1.1.3/class.html ## for discussion of arguments to addTimeSignature() ## including clocks_per_tick. if denominator == 16 and (numerator % 3 == 0): metro_clocks = 18 elif denominator == 16: metro_clocks = 6 elif denominator == 8 and (numerator % 3 == 0): metro_clocks = 36 elif denominator == 8: metro_clocks = 12 elif denominator == 4: metro_clocks = 24 elif denominator == 2: metro_clocks = 48 MyMIDI.addTimeSignature(track, time, numerator, denominator=midi_denom, clocks_per_tick=metro_clocks) elif m[0] == 'I' and metronome != 1: ## Instrument change time = m[1] instrument = m[2] - 1 ## convert to 0 index track = m[3] + 1 chan = m[4] - 1 MyMIDI.addProgramChange(track, chan, time, instrument) def add_notes(source, trk): """ Add all notes in source to trk on chan. """ for pitch, start, stop, velocity, chan in source: if pitch is not None: MyMIDI.addNote(trk, chan - 1, pitch, start, stop - start, int(velocity * 127)) if metronome == 0: for track, notes in enumerate(parts): add_notes(notes, track) elif metronome == 1: ## Metronome output only. add_notes(metronotes, trk0) else: ## Both for track, notes in enumerate(parts): add_notes(notes, track) metrotrack = numparts ## because 0-indexing add_notes(metronotes, metrotrack) with open(outfile, "wb") as output_file: MyMIDI.writeFile(output_file) if not quiet: for partnum, pmap in beat_map.items(): print_beat_map(partnum, pmap, first_bar_number=firstbar)
def write_midi(save_path, colors, draw_mode): # Create midi object display_state('Creating MIDI file') midi = MIDIFile(1, file_format=1) # Set time signature, tempo and instrument display_state('Adding time signature') midi.addTimeSignature(0, 0, 4, 2, 24) display_state('Adding tempo') midi.addTempo(0, 0, 120) display_state('Adding instrument') midi.addProgramChange(0, 0, 0, 0) # Convert to black and white if draw mode is on if draw_mode: display_state('Converting to black and white: Initiating') for y in range(len(colors)): str_y = (3 - len(str(y))) * '0' + str(y) for x, color in enumerate(colors[y]): str_x = (3 - len(str(x))) * '0' + str(x) display_state('Converting to black and white: Color ' + str_y + ', ' + str_x) colors[y][x] = (round( (color + 1) / 256) * 256) - 1 # Either -1 or 255 colors[y][ x] += 1 if colors[y][x] == -1 else 0 # Change -1 to 0 display_state('Converting to black and white: Finished') # Add all notes display_state('Adding notes to file: Calculating lowest note') lowest_note = round((132 - len(colors)) / 2) - 1 lowest_note += 1 if lowest_note == -1 else 0 display_state('Adding notes to file: Calculating lowest note: ' + str(lowest_note)) for y in range(len(colors)): str_y = (3 - len(str(y))) * '0' + str(y) for x, color in enumerate(colors[y]): str_x = (3 - len(str(x))) * '0' + str(x) display_state('Adding notes to file: Note ' + str_y + ', ' + str_x) if draw_mode and color == 0: midi.addNote(0, 0, lowest_note + (len(colors) - y), x, 1, 100) elif not draw_mode: midi.addNote(0, 0, lowest_note + (len(colors) - y), x, 1, color) display_state('Adding notes to file: Finished') # Save midi file display_state('Writing MIDI file to disk') if os.path.exists(save_path): os.remove(save_path) with open(save_path, 'wb') as file: midi.writeFile(file) display_state('Finished!') open_explorer = messagebox.askyesno( 'Finished!', 'The Image was successfully converted to a MIDI file.\n' 'The result can be found under ' + info['save_path'] + '\n\nDo you want to open the file explorer?', icon='info') if open_explorer: save_path_folder = '' for directory in save_path.split('/')[:-1]: save_path_folder += directory + '\\' subprocess.Popen('explorer "' + save_path_folder + '"')
# Makes and starts the thread playbackthread = threading.Thread(target=playback) playbackthread.daemon = True playbackthread.start() # Stops thread with any input input("Press enter to stop") stop_playback = 1 # Wait for thread to finish playbackthread.join() # Creates the midi file with tempo and time signature MyMIDI = MIDIFile(1) MyMIDI.addTempo(0, 0, int(bpm)) MyMIDI.addTimeSignature(0, 0, int(measure[0]), int(math.log2(int(measure[1]))), 24, 8) # Writes notes to midi file for i in range(int(sixteenths)): for x in range(3): # Choose note per drum according to general midi if x == 0: pitch = 42 elif x == 1: pitch = 38 elif x == 2: pitch = 36 if play_notes[i][x] == 1: # Probability gets scaled to velocity, higher chance is more likely to be an accent MyMIDI.addNote(0, 9, pitch, (i / 4), 0.25, int(60 + (67 * prob[i][x])))
snarePlaced=0 elif snarePlaced==0: if randint(0, 1) > 0: listSnare.append(x) snarePlaced=1 for x in range(steps): if miscPlaced==1: miscPlaced=0 elif miscPlaced==0: if randint(0,1)>0: listMisc.append(x) miscPlaced=1 #making midifile and copying lists for playback. MyMIDI.addTimeSignature(track, 0, numerator, denominator, metronome) playListMisc=copy.copy(listMisc) playListKick=copy.copy(listKick) playListSnare=copy.copy(listSnare) #plays back every list using the pop() function and a for loop. Writes midi file simeltaneously def playSequence(): playListMisc=copy.copy(listMisc) playListKick=copy.copy(listKick) playListSnare=copy.copy(listSnare) for x in range(steps): if len(playListKick)>0: if playListKick[0]==x: play_obj = KICK.play() MyMIDI.addNote(track, channel, 60, x, duration, velocity) playListKick.pop(0)
from midiutil import MIDIFile track = 0 channel = 9 time = 0 duration = 1 bpm = 200 velocity = 100 MyMIDI = MIDIFile(2) MyMIDI.addTempo(track, time, bpm) MyMIDI.addTimeSignature(track, 0, 7, 2, 24) MyMIDI.addNote(track, channel, 35, 0, duration, velocity) MyMIDI.addNote(track, channel, 38, 3 * duration, duration, velocity) MyMIDI.addNote(track, channel, 38, 5 * duration, duration, velocity) for i in range(7): MyMIDI.addNote(track, channel, 42, (time + i) * duration, duration, velocity) with open("beat.mid", "wb") as output_file: MyMIDI.writeFile(output_file)
elif (recordType == 1): # MIDI data block hashKey = createKey(str(recordNumber), str(recordMidiID)) debugPrint("Hash key is {}".format(hashKey)) # Have we seen a section header with this MIDI ID? midiSection = recordHash.get(hashKey) if (midiSection != None): debugPrint("Found MIDI data for section {}".format( midiSection.label)) # Create a new MIDIFile object to store the notes for this MIDI section midiFileData = MIDIFile(numTracks=trackLimit, ticks_per_quarternote=960, eventtime_is_ticks=True) midiFileData.addTimeSignature(0, 0, numerator, denominator, clocks_per_tick=24, notes_per_quarter=8) midiFileData.addTempo(0, 0, songTempo) midiFileData.addTrackName( 0, 0, midiSection.label + "-" + str(recordNumber) + "_" + str(recordMidiID)) trackCounter = 0 trackDict = dict() midiEvent = None lastMIDIEvent = None s.pos = dataStart while True: