I want to convert a sequence of notes (defined by time, duration, pitch) to a audio-file. For doing so, I thought creating a midi first and then compile it to wav is the way to go.
I'm quite new to audio processing and MIDI-Files, so even though I read several tutorials, it can be, that I didn't get the point.
Edit: I found the problem, see solution below.
What's the problem
Writing notes at a specific time with a specific duration via python's MIDIUtil
doesn't work as expected. In fact, the time in seconds, where a note is placed heavily depends on the track's bpm, even though I think I took the bpm into account, when converting the note time to MIDI's time measure in quarter notes.
What I've tried
I'm creating a MIDI track with a given bpm.
Then I'm converting a note's event time via
t_{quarter} = t_{seconds} * bpm/60
Example
I'm writing with the following code two notes, the last at t=5 seconds with a duration of 1s; i.e. I'm expecting a midi-file with lasts 6seconds. But at a bpm=600, the file is 14s long. At a bpm=100 it's almost the expected 6s.
Here's my code
from midiutil import MIDIFile
def convert_seconds_to_quarter(time_in_sec, bpm):
quarter_per_second = (bpm/60)
time_in_quarter = time_in_sec * quarter_per_second
return time_in_quarter
def write_test_midi():
bpm = 600
MyMIDI = MIDIFile(1)
MyMIDI.addTrackName(track=0, time=0, trackName="Sample Track")
MyMIDI.addTempo(track=0, time=0, tempo=bpm)
MyMIDI.addNote(track=0, channel=0, pitch=60,
time=convert_seconds_to_quarter(1, bpm),
duration=convert_seconds_to_quarter(1, bpm), volume=100)
MyMIDI.addNote(track=0, channel=0, pitch=60,
time=convert_seconds_to_quarter(5, bpm),
duration=convert_seconds_to_quarter(1, bpm), volume=100)
with open("/tmp/output.mid", 'wb') as binfile:
MyMIDI.writeFile(binfile)
Additional infos
The hex content of the file with bpm=100
:
ADDRESS 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ASCII
00000010 4d 54 68 64 00 00 00 06 00 01 00 02 03 c0 4d 54 MThd..........MT
00000020 72 6b 00 00 00 0b 00 ff 51 03 09 27 c0 00 ff 2f rk......Q..'.../
00000030 00 4d 54 72 6b 00 00 00 28 00 ff 03 0c 53 61 6d .MTrk...(....Sam
00000040 70 6c 65 20 54 72 61 63 6b 8c 40 90 3c 64 8c 40 ple.Track.@.<d.@
00000050 80 3c 64 a5 40 90 3c 64 8c 40 80 3c 64 00 ff 2f .<d.@.<d.@.<d../
00000060 00 00 00 00 .
The content of the file with bpm=600
:
ADDRESS 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ASCII
00000010 4d 54 68 64 00 00 00 06 00 01 00 02 03 c0 4d 54 MThd..........MT
00000020 72 6b 00 00 00 0b 00 ff 51 03 01 86 a0 00 ff 2f rk......Q....../
00000030 00 4d 54 72 6b 00 00 00 29 00 ff 03 0c 53 61 6d .MTrk...)....Sam
00000040 70 6c 65 20 54 72 61 63 6b cb 00 90 3c 64 cb 00 ple.Track...<d..
00000050 80 3c 64 81 e1 00 90 3c 64 cb 00 80 3c 64 00 ff .<d....<d...<d..
00000060 2f 00 00 00 /.
Solution
The code, conversion function and files I posted are all correct. The problem was the VLC player which I used to listening to the midi.