So I have this code to load in an audio file and play it:
export function Note(props) {
const [played, setPlayed] = useState(false);
const noteDiv = useRef();
const play = useRef();
const [isPlaying, setIsPlaying] = useState(false);
const note = useRef();
const audioContext = useRef(new (window.AudioContext || window.webkitAudioContext)());
// gets the file as an Audio Buffer
useEffect(() => {
fetch(props.filePath)
.then(data => {
// console log goes here
return data.arrayBuffer();
})
.then(arrayBuffer => {
const decode = audioContext.current.decodeAudioData(arrayBuffer);
return decode;
})
.then(decodedAudio => {
note.current = decodedAudio;
});
}, []);
const playNote = async () => {
if (audioContext.state === "suspended") {
await audioContext.current.resume();
}
const play = audioContext.current.createBufferSource();
play.buffer = note.current;
play.connect(audioContext.current.destination);
play.start();
};
// This component constantly renders as its state changes constantly while the playhead moves
useEffect(() => {
setPlayed(isPlayed(props.progress));
}, [props.progress]);
useEffect(() => {
if (played) {
playNote();
} else {
stopNote();
}
}, [played]);
return (
<div></div>
);
}
Basically, a playhead moves across the screen, and when a note is underneath it, the note plays an audio file.
For some reason, when I run the code and the playhead starts moving, no sound is heard even though the play.start() is called.
But, if I change something in the code, it works for some reason. For example, if I add a console log where I indicated and go back to my browser, the sound plays.
Is this because the Note component is rerendering? Why isn't just having the play.start() call itself not playing anything?
The filepath is correct and I can see that a file is loaded, and that an AudioBufferSourcenode is created with it. It's just the start() method that isn't working.