Skip to content

Instantly share code, notes, and snippets.

@misterhat
Created April 12, 2022 14:14
Show Gist options
  • Save misterhat/8962fcce3387c06dd932dbcfc2a32d53 to your computer and use it in GitHub Desktop.
Save misterhat/8962fcce3387c06dd932dbcfc2a32d53 to your computer and use it in GitHub Desktop.
dump a MIDI to PCM with tinysoundfont
#include <stdint.h>
#include <stdio.h>
#define TSF_IMPLEMENTATION
#include "tsf.h"
#define TML_IMPLEMENTATION
#include "tml.h"
#define SAMPLE_RATE 22050
#define CHANNELS 1
#define PCM_BUFFER_SIZE (SAMPLE_RATE * CHANNELS * 45)
#define RENDER_BUFFER_SIZE (SAMPLE_RATE * CHANNELS * 5)
uint8_t pcm_out[PCM_BUFFER_SIZE] = {0};
volatile int sound_position = -1;
tsf *soundfont = NULL;
tml_message *midi_loader = NULL;
tml_message *midi_render_short(tsf *soundfont, tml_message *midi_message, uint8_t *buffer,
int samples) {
int block_size = TSF_RENDER_EFFECTSAMPLEBLOCK;
int bytes_written = 0;
double msecs = 0;
do {
msecs += block_size * (1000.0 / SAMPLE_RATE);
while (midi_message && msecs >= midi_message->time) {
switch (midi_message->type) {
case TML_PROGRAM_CHANGE:
tsf_channel_set_presetnumber(
soundfont, midi_message->channel, midi_message->program,
(midi_message->channel == 9));
break;
case TML_NOTE_ON:
tsf_channel_note_on(soundfont, midi_message->channel,
midi_message->key,
midi_message->velocity / 127.0f);
break;
case TML_NOTE_OFF:
tsf_channel_note_off(soundfont, midi_message->channel,
midi_message->key);
break;
case TML_PITCH_BEND:
tsf_channel_set_pitchwheel(soundfont, midi_message->channel,
midi_message->pitch_bend);
break;
case TML_CONTROL_CHANGE:
tsf_channel_midi_control(soundfont, midi_message->channel,
midi_message->control,
midi_message->control_value);
break;
}
midi_message = midi_message->next;
}
tsf_render_short(soundfont, (int16_t*)(buffer + bytes_written), block_size, 0);
bytes_written += block_size * 2;
} while (bytes_written < samples);
return midi_message;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment