I am trying to write a simple interface for creating MIDI files. As a test, I tried to create a file that plays a major scale, all notes of the same length. The file I get is as follows (indented for readability)
4d 54 68 64 00 00 00 06 00 01 00 02 00 08
4d 54 72 6b 00 00 00 0b
00 ff 51 03 00 27 0f
00 ff 2f 00
4d 54 72 6b 00 00 00 54
00 c0 00
00 90 40 7f
7d 80 40 7f
7d 90 42 7f
81 7a 80 42 7f
81 7a 90 44 7f
82 77 80 44 7f
82 77 90 45 7f
83 74 80 45 7f
83 74 90 47 7f
84 71 80 47 7f
84 71 90 49 7f
85 6e 80 49 7f
85 6e 90 4b 7f
86 6b 80 4b 7f
86 6b 90 4c 7f
87 68 80 4c 7f
00 ff 2f 00
Explanations: Line 1 is file header. Line 2 is a track header. (In my interface I reserve one track for percussion, and also to set the tempo. Since I have no percussion in this example it contains no notes.) Line 3 sets the tempo, line 4 ends the track. Line 5 is another track header. This track contains the melody. Line 6 sets the instrument for channel 0. Next come 8 alternating note-on and 8 note-off events for channel 0, and then track end. Times for starting and ending notes are:
00, 7d, 81 7a, 82 77, 83 74, 84 71, 85 6e, 86 6b, 87 68
As far as I understand, they should be uniformly spaced, because for event times MIDI uses a 7-bit-byte format where the length of the number is flexible and all bytes except the last one have their msnzb set. So 00 should translate to 0, 7d should translate to 125, 81 7a should translate to 250, etc. But for some reason, when you play the file, it does not sound uniform time-wise, but rather slowing down. Why is it so? Have I misunderstood the correct way to encode event timing, and if yes then what would be the correct way? Or is there some other issue with my file that causes the problem?
Timestamps in a MIDI file are delta-times -- you don't encode the time that an event occurs, you encode the time difference between sequential events on that track. If events are evenly spaced in time, their delta times should be the same.
From the standard:
see e.g. http://www.music.mcgill.ca/~ich/classes/mumt306/StandardMIDIfileformat.html