-1

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.

iegrm
  • 57
  • 5

1 Answers1

2

I think the reason is that chrome and probably other browsers (firefox, edge, opera, etc.) don't want to surprise the user with a random sound. So as this thread explains, you need to first mute your audio and then you can play. After that you should be able to adjust the volume.

JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
Charles
  • 79
  • 2