Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!