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

144
Visualizações
Audio tag not working when called from JavaScript

I am adding my HTML & js file which I am using. I think there is problem in sound.play(), other than it complete code is working fine. I have checked it using console.

HTML

<body>
<audio id="sound">
</audio>
<button onclick="playSound()"><i class="fas fa-volume-up"></i></button>
</body>

JS

sound = document.getElementById("sound");
sound.setAttribute("src",https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3);
function playSound(){
    sound.play();
    console.log("hello");
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

...well, first off, maybe put quotes around your source URL, and when consider your HTML --> when you load your script in HTML header - browser will execute it after it's (the script) loaded, but the DOM content isn't loaded yet (simply, getElementById would return undefined ..., so (check the Dom / dom events and such, and either wrap the scripts' with i.e `window.addEventListener('DOMContentLoaded / load' ... ) :

<!doctype html>

<html>
  <head>
    <link rel="stylesheet" href="lib/style.css">
  </head>

  

I am adding my HTML & js file which i am using. I think their is problem in sound.play(), other than it complete code is working fine. I have checked it using console.

HTML

<body>
<audio id="sound">
</audio>
<button onclick="playSound()"><i class="fas fa-volume-up">Play</i></button>
    <script src="lib/script.js"></script>
</body>
</html>
const sound = document.getElementById("sound");
sound.setAttribute("src", "https://api.dictionaryapi.dev/media/pronunciations/en/hello-uk.mp3");

function playSound() {
  sound.play();
  console.log("hello");
}
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