Estoy agregando mi archivo HTML & js que estoy usando. Creo que hay un problema en sound.play(), aparte de que el código completo funciona bien. Lo he comprobado usando consola.
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"); }... bueno, en primer lugar, tal vez ponga comillas alrededor de su URL de origen, y cuando considere su HTML -> cuando cargue su secuencia de script en el encabezado HTML, el navegador lo ejecutará después de que se cargue (la secuencia de comandos), pero el contenido DOM es 'todavía no se ha cargado (simplemente, getElementById devolvería indefinido..., así que (verifique los eventos Dom/dom y demás, y envuelva los scripts' con, por ejemplo, '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"); }