Así que tengo un sitio web de piano donde puedes dibujar notas en una pantalla y presionar un botón para iniciar un cabezal de reproducción, y a medida que el cabezal de reproducción se mueve a lo largo de la pantalla, se reproducen las notas debajo de él. Estoy usando la aplicación Create React y uso npm start para iniciar la aplicación en Chrome
Este es el método del botón onClick:
const onClick = async () => { setPlay((prev) => prev ? "" : "play"); if (audioContext.state === 'suspended') { await audioContext.resume(); console.log("resumed"); console.log(audioContext.state); } }; A medida que avanza el cabezal de reproducción, tengo un accesorio llamado progress que almacena ese valor y actualiza cada cuadro (por lo tanto, 30 fps)
Este es el código de una nota que el usuario dibuja.
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> ); }Me aseguré de reanudar el contexto de audio al hacer clic en el botón. Pero por alguna razón, el sonido simplemente no se reproduce. ¿Estoy haciendo algo mal?
Editar: la ruta del archivo parece ser correcta porque puedo ver que el archivo se está cargando en la red
Este código funciona bien:
<!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); });Echa un vistazo a: