I have a component which uses Soundfont to play a note which loads by useEffect.
useEffect(() => { // fix loading
const ac = new AudioContext();
soundfontInstrument(ac, 'acoustic_grand_piano', { soundfont: 'MusyngKite' })
.then((acoustic_grand_piano) => {
somePiano = acoustic_grand_piano;
setPiano(acoustic_grand_piano);
console.log("piano is ready");
setIsPianoReady(true);
});
return () => {
ac.close();
};
}, []);
When I load the page the first time, setPiano and setIsPianoReady is called as expected but the button doesnt play any sound. It is until I refresh the page or reload the component that it only plays sound. The useEffect is a child component.
I have tried using async and await functions for my playNote function but it doesnt work either. I was expecting the Soundfont to actually play sound
async function handlePlayNote() {
if (piano) {
try {
if (Array.isArray(tone)) {
if (questionType === 'scales'){
// Play notes sequentially with a delay
for (const note of tone) {
await piano.play(note);
// Introduce a delay between notes
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.log("Played notes: " + tone.join(', '));
} else {
await Promise.all(tone.map(note => piano.play(note)));
console.log("Played notes: " + tone.join(', '));
}
} else {
console.error("Invalid tone format:", tone);
}
} catch (error) {
console.error("Error playing notes:", error);
}
} else {
console.log("Piano not ready");
}
}