Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
Web Audio API not playing sound

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

chrome://settings/content?search=sound

Sound Chrome settings

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda