Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a MIDI file with Python?

Tags:

python

midi

I am writing a script to convert a picture into MIDI notes based on the RGBA values of the individual pixels. However, I cannot seem to get the last step working, which is to actually output the notes to a file.

I have tried using the MIDIUtil library, however its documentation is not the greatest and I can't seem to figure it out.

If anyone could tell me how to sequence the notes (so that they don't all begin at the beginning) it would be greatly appreciated.

like image 903
pstap92 Avatar asked Jun 16 '12 00:06

pstap92


People also ask

What is Mido in Python?

Mido is a library for working with MIDI messages and ports: >>> import mido >>> msg = mido.

How are MIDI files encoded?

To any file system, a MIDI File is simply a series of 8-bit bytes. On the Macintosh, this byte stream is stored in the data fork of a file (with file type 'MIDI'), or on the Clipboard (with data type 'MIDI'). Most other computers store 8-bit byte streams in files.

What is MIDI BPM?

BPM. Unlike music, tempo in MIDI is not given as beats per minute, but rather in microseconds per beat. The default tempo is 500000 microseconds per beat, which is 120 beats per minute. The meta message 'set_tempo' can be used to change tempo during a song.


1 Answers

Looking at the sample, something like

from midiutil.MidiFile import MIDIFile

# create your MIDI object
mf = MIDIFile(1)     # only 1 track
track = 0   # the only track

time = 0    # start at the beginning
mf.addTrackName(track, time, "Sample Track")
mf.addTempo(track, time, 120)

# add some notes
channel = 0
volume = 100

pitch = 60           # C4 (middle C)
time = 0             # start on beat 0
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

pitch = 64           # E4
time = 2             # start on beat 2
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

pitch = 67           # G4
time = 4             # start on beat 4
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

# write it to disk
with open("output.mid", 'wb') as outf:
    mf.writeFile(outf)
like image 89
Hugh Bothwell Avatar answered Oct 24 '22 09:10

Hugh Bothwell