0

I have this method to play some audio:

playAudio() {
    const audio = new Audio(
        "/some-audio.mp3"
    );

    audio.play();

}

And this playAudio() method is then triggered via some websocket event (no click is triggered from the user):

someWebSocketEvent() {
   this.playAudio();
}

The audio wouldn't play. However, if a click event triggers this audio, then it will work. Looking around, it's some web browser policy that is preventing the audio element to play unless there's a click event but not sure how to bypass this.

Is there any way to make this work?

catandmouse
  • 11,309
  • 23
  • 92
  • 150

1 Answers1

0

You can simulate clicks, but I don't know if it will be blocked, Can try it.

var anchor = document.createElement('a');

anchor.onclick = function() {
    var audio = new Audio();

    audio.onload = function() { audio.play(); }

    audio.src= 'audio.mp3';
}

anchor.click();
Yulin Han
  • 21
  • 2