10

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.

6

2 Answers 2

14

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.

5
  • 17
    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, 2021 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, 2021 at 4:03
  • 1
    "Some interaction" But there is no list on what that does mean, scrolling does not count, nor confirming alert, seems only click ? Jan 18, 2022 at 16:39
  • @avisk I think it's built-in Chrome(ium) feature Apr 22 at 7:36
  • @avisk based on this post developer.chrome.com/blog/autoplay it seems like they follow their own policy, even if it looks like an arbitrary one Nov 7 at 9:01
6
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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.