MIDI File Structure

What is a MIDI file?

MIDI (Musical Instrument Digital Interface) contains a set of instructions that tell how and when instruments are played. It does not contain any actual audio data, just when a note is on or off and different properties for the note. MIDI file consists of chunks. The first chunk is always the header chunk. After the header chunk comes any amount of track chunks. MIDI files are big-endian binary files.



Header chunk

The header chunk contains information of the file itself. Here are the header chunk's fields in order:

(the names are not "official", it's just what I call them)
Name Byte sizeValue Notes
Prefix 4 0x4d546864, "MThd" Always the string "MThd". If the file starts with this string then it is a MIDI file.
Header length 4 0x00000006 Length of the rest of the header chunk. Always 6 bytes long.
Format 2 0 if this is a single track file
1 if this is a multiple track file
2 if this is a multiple song file (series of MIDI files)
Number of tracks 2 Number of tracks in the file
Division / Timing 2 "unit of time for delta timing"

I will explain (or atleast try to) delta timings in an another post.

Track chunks

The track chunks contain information of the instruments, notes, copyrights etc. Here are the track chunks' fields in order:

NameByte size Value
Notes
Prefix 4 0x4d54726b, "MTrk" This is the sign that a track chunk starts from here.
Track length 4 Number of bytes in the track starting from the byte after this.
All track events Defined in the previous field Sequence of different track events

There are many types of track events that I will explain in an another post.


Example

Let's look at these bytes and what they tell us:
4d 54 68 64 00 00 00 06 00 01 00 03 00 c0 4d 54 72 6b 00 00 01 4b ...
We can separate them into fields now that we know their byte size:
4d 54 68 64 00 00 00 06 00 01 00 03 00 c0 4d 54 72 6b 00 00 01 4b ...
In order:
  • Yellow: We can see that the byte array starts with 4d546864 (MThd) so it is a midi file
  • Purple: The size of the header chunk is 6 bytes which is also correct
  • Blue: The format of this midi file is 1 so we know that the file contains multiple tracks
  • Green: Now we know that the file has three tracks
  • Red: The delta timing is 192 (explained later what this means)
  • Yellow again: First track chunk starts (MTrk)
  • Purple again: The byte length of the following events in this track is 33

Other great sources


Last updated 2017-11-01 16:02:21 UTC

Email

santeri.nogelainen@gmail.com

Discord

santerinog (#4652)

Skype

pinguu9999 (don't judge lol... this is a club penguin era username and I can't change it)

I prefer Email and Discord but Skype is fine I guess.
EMAIL

PASSWORD