So I have a piano website where you can draw in notes on a screen and press a button to start a playhead, and as the playhead moves along the screen, the notes under it get played. I'm using the Create React app and using npm start to launch the app on Chrome
This is the button onClick method:
const onClick = async () => {
setPlay((prev) => prev ? "" : "play");
if (audioContext.state === 'suspended') {
await audioContext.resume();
console.log("resumed");
console.log(audioContext.state);
}
};
As the playhead progress, I have a prop called progress that stores that value and updates every frame (so 30fps)
This is the code for a note that the user draws in.
export function Note(props) {
const audioContext = new AudioContext();
let note;
// fetching the audio from file in the public folder
fetch(props.filePath)
.then(data => data.arrayBuffer())
.then(arrayBuffer => audioContext.decodeAudioData(arrayBuffer))
.then(decodedAudio => {
note = decodedAudio;
});
const isPlayed = (offset) => {
// returns boolean if note is being played or note
};
// stores current progress
useEffect(() => {
setPlayed(isPlayed(props.progress));
}, [props.progress]);
// plays note if played value changes
useEffect(() => {
if (played) {
playNote();
} else {
audioContext.suspend();
}
}, [played]);
// plays note
const playNote = () => {
const play = audioContext.createBufferSource();
play.buffer = note;
play.connect(audioContext.destination);
play.start();
};
return (
// displays the note on screen
<div><div>
);
}
I made sure to resume the Audio Context upon button click. But for some reason, the sound just isn't playing. Am I doing something wrong?
Edit: the file Path seems to be correct because I can see the file being loaded in the network
This code works ok:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script src="playNote.js"></script>
</head>
<body>
<button id="playButton">Play Sound</button>
</body>
</html>
playNote.js
const audioContext = new AudioContext();
let note;
// fetching the audio from file in the the same folder that this file
fetch('beach.mp3')
.then(data => data.arrayBuffer())
.then(arrayBuffer =>
audioContext.decodeAudioData(arrayBuffer))
.then(decodedAudio => {
note = decodedAudio;
})
const playNote = () => {
const play = audioContext.createBufferSource();
play.buffer = note;
play.connect(audioContext.destination);
play.start();
};
function handleClick() {
playNote()
}
window.addEventListener('load', (event) => {
const playButton = document.getElementById('playButton')
playButton.addEventListener("click", handleClick);
});
Take a look to: