Goffredo Haus, editor
Fall 1995
© IEEE Computer Society Press.
3.5. Program Fragments and Example MIDI Files
Here are some of the routines to read and write variable-length numbers in MIDI Files. These routines are in C, and use getc and putc, which read and write single 8-bit characters from/to the files infile and outfile.
WriteVarLen (value)
register long value;
{
- register long buffer;
- buffer = value & 0x7f;
- while ((value >>= 7) > 0)
- {
- buffer <<= 8;
- buffer |= 0x80;
- buffer += (value & 0x7f);
- }
- while (TRUE)
- {
- putc(buffer,outfile);
- if (buffer & 0x80)
- buffer >>= 8
- else
- break;
- }
}
doubleword ReadVarLen ()
{
- register doubleword value;
- register byte c;
- if ((value = getc(infile)) & 0x80)
- {
- value &= 0x7f;
- do
- {
- value = (value << 7) + ((c = getc(infile)) & 0x7f);
- } while (c & 0x80);
- }
- return (value);
- }
As an example, MIDI Files for the following excerpt are shown below. First, a format 0 file is shown, with all inforrnation intermingled; then, a format 1 file is shown with all data separated into four tracks: one for tempo and time signature, and three for the notes. A resolution of 96 "ticks" per quarter note is used. A time signature of 4/4 and a tempo of 120, though implied, are explicitly stated.

Figure 10 - Example of 3 parts excerpt.
The contents of the MIDI stream represented by this example are broken down here:

Table XXVIII
The entire formats 0 and 1 MIDI file contents in hex follow. First, the header chunk, then, the track chunk.

Table XXIX

Table XXX
[Index |
Main Paragraph |
Previous Paragraph ]