I am making a game with HTML5 and JavaScript.
How could I play game audio via JavaScript?
If you are getting the following error:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
That means the user needs to interact with the website first (as the error message says). In this case you need to use click
or just another event listener, so the user can interact with your website.
If you want to auto load the audio and don't want the user to interact with the document first, you could use setTimeout
.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
The sound will start after 0.5 second.