import sys
import csv
from midiutil.MidiFile import MIDIFile
import pygame.mixer
# Parse command line arguments
if len(sys.argv) != 2:
print("Usage: {} <input_csv>".format(sys.argv[0]))
sys.exit(1)
input_csv = sys.argv[1]
# Parse CSV file
pitches = []
durations = []
times = []
with open(input_csv, "r") as f:
reader = csv.reader(f)
for row in reader:
pitches.append(int(row[0]))
durations.append(int(row[1]))
times.append(float(row[2]))
# Generate MIDI file
midi_file = MIDIFile(1)
# Add track
track = 0
time = 0
midi_file.addTrackName(track, time, "Track1")
midi_file.addTempo(track, time, 120)
# Add notes
channel = 0
volume = 100
for i in range(len(pitches)):
pitch = pitches[i]
time = times[i]
duration = durations[i]
midi_file.addNote(track, channel, pitch, time, duration, volume)
# Save MIDI file
with open("temp.mid", "wb") as f:
midi_file.writeFile(f)
# Play MIDI file using pygame
pygame.mixer.init()
pygame.mixer.music.load("temp.mid")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
continue
Here is an example CSV file containing the first four bars of Ode To Joy:
60,2,0 60,2,0.5 67,2,1 67,2,1.5 69,2,2 69,2,2.5 67,4,3 65,2,4 65,2,4.5 64,2,5 64,2,5.5 62,2,6 62,2,6.5 60,2,7 60,2,7.5 67,2,8 67,2,8.5 69,2,9 69,2,9.5 67,4,10 65,2,11 65,2,11.5 64,2,12 64,2,12.5 62,2,13 62,2,13.5
This CSV file can be used as the input to the Python script above. Note that the time values in this file are in units of beats, with a tempo of 120 beats per minute.