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");
}
...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");
}