For a C++ project I'm working on, I'm wanting to use fluidsynth to read from a midi file, write it to a buffer, then use another library to play the midi from that buffer. However, for certain midis, the timing gets all messed up. Here's some code that produces the problem:
#include <fluidsynth.h>
#include <iostream>
#include <fstream>
#include <vector>
const int SAMPLE_LENGTH = 44100;
const int CHANNEL_NUMBER = 2;
const int SECONDS = 30;
std::vector<int16_t> samples(SAMPLE_LENGTH*CHANNEL_NUMBER*SECONDS);
fluid_settings_t* settings;
fluid_synth_t* synth;
fluid_player_t* player;
int main(int argc, char* argv[])
{
if (argc < 3) {
std::cout << "Please input a soundfont and midi file.";
return 1;
}
settings = new_fluid_settings();
synth = new_fluid_synth(settings);
if (fluid_synth_sfload(synth, argv[1], 1) == FLUID_FAILED) {
std::cerr << "Unable to open soundfount" << std::endl;
return 1;
}
player = new_fluid_player(synth);
if (fluid_player_add(player, argv[2]) == FLUID_FAILED) {
std::cerr << "Unable to open midi" << std::endl;
return 1;
}
if (fluid_player_play(player) == FLUID_FAILED) {
std::cerr << "Unable to play midi" << std::endl;
return 1;
}
if (fluid_synth_write_s16(synth, SAMPLE_LENGTH*SECONDS, &samples[0], 0, 2, &samples[0], 1, 2) == FLUID_FAILED) {
std::cerr << "Unable to write buffer" << std::endl;
return 1;
}
// Not what I actually want to do, but it will let you hear it straight from the buffer
std::ofstream file("sound.raw", std::ios::binary);
file.write((char*)&samples[0], samples.size() * 2);
file.close();
return 0;
}
Compile that, and run with "[program] [soundfont] [midi]", and it will output some raw audio data. With certain midis, this data's timing is off. I've attached two midis, "001-Battle01.mid" and "015-Theme04.mid". For 001Battle01.mid, it outputs fine. However, 015-Theme04.mid sound bad. I've attached another file, sound.ogg, which shows what it sounds like.
I've been trying several different things for a while, but nothing seems to be working. Can anybody help? Thank you!