Working example
I was able to build libfluidsynth-2.3.0.js but unable to get it working. This is what I have at this time:
Module.onRuntimeInitialized = async () => {
console.log("FluidSynth initialized");
const settings = Module._new_fluid_settings();
const synth = Module._new_fluid_synth(settings);
window.settings = settings;
window.synth = synth;
// Load the SoundFont
const response = await fetch("test.sf2");
const buffer = await response.arrayBuffer();
const uint8Array = new Uint8Array(buffer);
const dir = "/sf2";
const path = `${dir}/test.sf2`;
if (!Module.FS.analyzePath(dir).exists) {
Module.FS.mkdir(dir);
}
Module.FS.createDataFile(dir, "test.sf2", uint8Array, true, true);
console.log("FS:", Module.FS.readdir(dir));
const sfid = Module._fluid_synth_sfload(synth, path, 1);
console.log("sfload result:", sfid);
const errPtr = Module._fluid_synth_error(synth);
if (errPtr) {
console.log("FluidSynth error:", Module.UTF8ToString(errPtr));
}
};
I keep getting sfid = -1. I have verified the sf2 file is OK and loading. Is there a working example somewhere? (This code was generated by chatGPT)
const sfid = Module._fluid_synth_sfload(synth, path, 1);
Here, if you call Module._fluid_synth_sfload directly, path must be the pointer to the UTF-8 string (not JS string). The direct call of exported function (assigned into Module) does not convert between JS string and C/C++ string, so you need to convert it manually.
const pathLen = (path.length << 2) + 1;
const pathPtr = stackAlloc(pathLen);
stringToUTF8(path, pathPtr, pathLen);
const sfid = Module._fluid_synth_sfload(synth, pathPtr, 1);
Or, you can use Module.cwrap which wraps the function to call easier. js-synthesizer uses this as: https://github.com/jet2jet/js-synthesizer/blob/main/src/main/Synthesizer.ts#L83