GitHub Source

I recently took a detour exploring FM synthesis and MIDI parsers. FM waves, similar to that of generic DOS sound-card OPL waveforms, make for quite the neat little orchestra when fed directly to the sound-card through SDL2. The waveforms, mocking up various instruments like the piano, guitar, brass, and winds, are emulated by FM synthesizing either a triangle, sine, square, half triangle, or quarter sine waveform with another. Here I play Howard Shore’s Concerning Hobbits:

Instrument wise, an organ may be synthesized as a half triangle modulated by that of a sine wave:

static int16_t
(Wave_Organ)
(Wave* wave, Note* note, float fm)
{
    (void) fm;
    return Wave_FM(wave, note, Wave_TRH, Wave_SIN, 0.8f);
}

A small library of waveforms generators can be built and mapped to that of the General MIDI specification:

static int16_t
(*WAVE_WAVEFORMS[])(Wave* wave, Note* note, float fm) = {
    [  0 ] = Wave_Piano,
    [  1 ] = Wave_ChromaticPercussion,
    [  2 ] = Wave_Organ,
    [  3 ] = Wave_Guitar,
    [  4 ] = Wave_Bass,
    [  5 ] = Wave_Strings1,
    [  6 ] = Wave_Strings2,
    [  7 ] = Wave_Brass,
    [  8 ] = Wave_Reed,
    [  9 ] = Wave_Pipe,
    [ 10 ] = Wave_SynthLead,
    [ 11 ] = Wave_SynthPad,
    [ 12 ] = Wave_SynthEffects,
    [ 13 ] = Wave_Ethnic,
    [ 14 ] = Wave_Percussive,
    [ 15 ] = Wave_SoundEffects,
};

Once a couple threads are initialized, one to parse a MIDI file and “turn on and off” instruments, and another thread to generate the appropriate waveforms for the sound card, an orchestra is emulated purely from that of programming text and some fundamental mathematics.

Try giving giving the source a read. The source resides in a single file, with a single consumer thread, a producer thread, and a small video driver to draw the waveforms on screen with zero phase offset.