Created
June 7, 2022 06:03
-
-
Save kevinlinxc/54da6493ddd1aaed959e1b3b72afc0e2 to your computer and use it in GitHub Desktop.
Convert Basic Pitch CSV into MIDI with MIDIUtil
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# unsuccessful attempt to convert the basic pitch csv into sheet music. Difficult because converting seconds to beats is difficult | |
from midiutil.MidiFile import MIDIFile | |
from csv import reader | |
import sys | |
hard_coded_start_time = 1.184217687 | |
def csv_to_midi(csv_path, output_path): | |
bpm = 72 # bpm | |
mf = MIDIFile(2) | |
track = 0 | |
midi_time = 0 | |
mf.addTrackName(track, midi_time, "Track 1") | |
mf.addTempo(track, midi_time, bpm) | |
channel = 0 | |
with open(csv_path, 'r') as read_obj: | |
csv_reader = reader(read_obj) | |
header = next(csv_reader) # skip header | |
last_was_blank = False | |
if header is not None: | |
for row in csv_reader: | |
if len(row) == 0: | |
if last_was_blank: # if two blanks in a row, stop | |
break | |
last_was_blank = True | |
continue # skip blank rows | |
last_was_blank = False | |
start_time, end_time, pitch, velocity = row[0:4] | |
start_time_beats = bpm/60 * (float(start_time) - hard_coded_start_time) | |
end_time_beats = bpm/60 * (float(end_time)- hard_coded_start_time) | |
pitch = int(pitch) | |
velocity = int(velocity) | |
duration_beats = end_time_beats-start_time_beats | |
mf.addNote(track, channel, pitch, start_time_beats, duration_beats, velocity) | |
with open(output_path, 'wb') as outfile: | |
mf.writeFile(outfile) | |
if __name__ == "__main__": | |
assert len(sys.argv) == 3 | |
csv_to_midi(sys.argv[1], sys.argv[2]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment