2
playSound : function() {
      var audio = new Audio(audio.mp3);
      audio.play();
 }

I am using the above code to simply play audio. But I am facing two issues below:

  1. The sound never plays till I click on the tab (for this I go to another tab and then click the current tab). Seems it needs an event before playing sound.
  2. Sometimes I get exception and audio never plays "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first."

I don't want to mess with HTML element.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29
pankaj
  • 159
  • 10

1 Answers1

0

You're likely seeing the policy change for autoplaying media on websites issued by Chrome: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

In essence, the policy says that unless the user interacts on your media and your handler* does not start the media synchronously, it will not play.

Notice the word synchronously - you can't even use setTimeout or some such. This is to protect the user from spammy ads and alike. The other browsers have this as well, as a setting, but they might and likely will enable this by default, so you better get ready for it.

[*] - (e.g. click handler)

Zlatko
  • 18,936
  • 14
  • 70
  • 123
  • Thanks, So can't I do anything from my side except waiting? – pankaj May 15 '18 at 07:09
  • You can read a little on that page - once the user crosses his "media engagement index" with your site - e.g. install on home screen, play your video/audio a few times or similar - your autoplay will start working again. Check what they offer you and then you can create a strategy. – Zlatko May 15 '18 at 07:23
  • But I can not see anything I can do with "media engagement index" within my code. Seems it will not let me play without user interation. Do I need to add audio tag? – pankaj May 15 '18 at 14:05
  • The **MEI** is not on your end: it's based on how often in the past has the user played your media longer than 7 seconds. Basically, if you offer sound and the users never play it, it will never autoplay. But if you offer sound with autoplay and the user clicks "play" and sees to 7 seconds of the media in question, then _next_ time he lands on your page your autoplay will work. – Zlatko May 16 '18 at 08:48