Skip to content
Advertisement

How to extract tempo from MIDI file

I am using the sequence.getResolution() built in method to extract how long a beat is in milliseconds. It works for some songs but not all. For example, for the song ‘sweet home alabama’ it returns a beat of 384 MS, however in real life the actual beat length is 612 MS. This works for countless other songs and only works for one of the songs that I am working with.

Any other way to correctly extract the bpm or tempo of a MIDI file using java would be greatly appreciated

Advertisement

Answer

The tempo is automatically defined in the MIDI file. Using the MetaMessage Class in javax.sound.MIDI and the method getData() you will obtain the bytes of metadata. The bytes labeled 0x51 holds the value of the tempo measured in microseconds per quarter note for each track. Note, each MIDI file generally has multiple tracks; hence multiple tempo signatures. Look at the outline of the MIDI structure link below. It explains each piece of the MIDI file data and where and what everything means.

Here is a link to an outline of the MIDI structure: http://www.ccarh.org/courses/253/handout/smf/

Here is a link to the MetaMessage Class: https://docs.oracle.com/javase/8/docs/api/javax/sound/midi/MetaMessage.html

Here is a link to the standard MIDI file format: https://formats.kaitai.io/standard_midi_file/index.html

Simple summary: 11th and 12th byte = number of tracks. This is located in the header which is 14 bytes long. Following that is a track chunk, and then another, and another as many times as defined by the 11th and 12th bytes. Each one has a length defined in the 5, 6, 7, and 8 bytes in the chunk. The length measures how many bytes the track is (starting on the 9th byte).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement