7

I'm trying to play a sound on a web page using javascript but whenever I do, I get the above error. Here's my code:

if (thing.startsWith("0")) {
    var a = new Audio("audio.mp4");
    a.play();
}

Furthermore, if you open the console, the sound automatically starts playing.

avisk
  • 330
  • 2
  • 6
  • 16
  • Where is the error? – Levi Blodgett Nov 13 '19 at 21:46
  • 1
    In the console. – avisk Nov 13 '19 at 21:47
  • Possible duplicate of [How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?](https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use) – Tyler Roper Nov 13 '19 at 21:51
  • No, I mean you didn't include the error in the question, you said "I get the above error" but there is no error in the question. – Levi Blodgett Nov 13 '19 at 21:51
  • @LeviBlodgett It's the title of the question. – Tyler Roper Nov 13 '19 at 21:51
  • OP, consider checking this out: [Autoplay Policy Changes](https://developers.google.com/web/updates/2017/09/autoplay-policy-changes), which states *"Chrome's autoplay policies are simple: Muted autoplay is always allowed. Autoplay with sound is allowed if the user has interacted with the domain (click, tap, etc.)."* – Tyler Roper Nov 13 '19 at 21:54

2 Answers2

12

It´s because Google updated its Autoplay Policy, it is necessary for the user to make some interaction first with the window in which the sound will be played, for example a 'Start' button then you can play the sound. This happened because for many users it is annoying when a sound is played out of nowhere.

asdf31
  • 178
  • 1
  • 12
  • 15
    I know this is an old post, but it's kinda funny how Youtube is owned by Google and still to this day does not follow that policy. – avisk Aug 18 '21 at 21:52
  • @avisk, is the technique YouTube uses known? Some might try to investigate personally, but perhaps it's already shared. – Artfaith Dec 21 '21 at 04:03
  • 1
    "Some interaction" But there is no list on what that does mean, scrolling does not count, nor confirming alert, seems only click ? – Jiro Matchonson Jan 18 '22 at 16:39
  • @avisk I think it's built-in Chrome(ium) feature – RomanistHere Apr 22 '23 at 07:36
5
var resp = audio.play();

if (resp!== undefined) {
    resp.then(_ => {
        // autoplay starts!
    }).catch(error => {
       //show error
    });
}

This code helped me remove the warning form the console

Yash
  • 59
  • 1
  • 1