So I'm making a piano website where the user can draw in notes and play them. A playhead goes across the screen and whatever notes are under it get played.
I have a state called played for each note which tracks if the note is being played or not.
const note = useRef(new Audio(props.filePath));
note.current.preload = "auto";
useEffect(() => {
if (played) {
note.current.play();
} else {
note.current.pause();
}
}, [played]);
I have a useRef to access the sound to prevent it from reloading when the component renders.
I also have a state called progress which constantly updates as the playhead moves. But I don't think this should be an issue since the sound is preloaded.
My problem is that even though the .play() command executes, the sound still takes a few seconds to be heard.
For example, right after the .play() call, I logged the note.paused value, which came out false. So this means that the note is being played, but I just can't hear it.
For some reason, if a note is currently playing, and the playhead loops back and plays the same note again, the sound is heard instantly. But if I pause the playhead and wait for the audio to end, and then play again, the delay is back.
So how do I make it so that the note is heard as soon as the playhead reaches the note everytime?