I'm developing a multiplayer card game using websockets with HTML/JS, it involves each player taking a turn and I'd like an audio alert to play when it's your turn.
function PlayAudio(sound) {
var audio = new Audio(sound);
audio.volume = 0.5;
audio.play();
}
This isn't possible if the user hasn't done an action to cause that audio to play or if the user switches tab, the following error is returned in the console:
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
I encountered an issue like this before with video playback - video cannot play automatically without user interaction unless muted.
What are websites like Youtube doing to bypass this restriction, or do they just get special treatment? Youtube videos autoplay with audio on page load.