Sunday, July 24, 2016

MIDI Variable Length Value Code

I added a Type 1 MIDI export function to my sequencer software today, so I thought I'd post the MIDI delta time code I used as I couldn't find any other code snippets online.

lword tempstore[4], tempstorecounter, i, deltatime, trackbuffersize;
char trackbuffer[];
.
.
.
// This will convert a long word time variable in deltatime into variable bit rate MIDI delta time
// format, storing it as a string of chars in "trackbuffer"
// tempstore is used to invert the significance of the bits, as the MBS's need to come first

for (tempstorecounter=0; deltatime>127; deltatime=(deltatime>>7))
tempstore[tempstorecounter++]=(char)(deltatime&0x7f);
tempstore[tempstorecounter++]=deltatime;
for (i=0; i<tempstorecounter; i++)
{
if (i<tempstorecounter-1)
trackbuffer[trackbuffersize++]=(char)(0x80|tempstore[tempstorecounter-1-i]);
else
trackbuffer[trackbuffersize++]=(char)tempstore[tempstorecounter-1-i];
}