Search code examples
javascriptjqueryhtml5-audio

JS Auto play background audio after window reload


I've tried auto play the audio as background music. When I open page, it's ok. But when I reload page, It cannot play. Console log error:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

My code:

$(window).on('load', function() {
    var soundSpin = new Audio('../images/gift/spin.mp3');
    soundSpin.muted = false;
    soundSpin.play();
    soundSpin.addEventListener('ended', function() {
        soundSpin.currentTime = 0;
        soundSpin.play();
    }, false);
});

How can I fix it? Thank you so much.


Solution

  • There's nothing wrong with your code. Modern browsers disable autoplay by default unless certain criteria are met. In general, one of the following will allow autoplay:

    1. The user clicks on the page*
    2. The media does not have audio or the audio is muted by default
    3. The user has explicitly whitelisted the page to autoplay media with audio
    4. The browser enables autoplay after detecting the user interacts with the page frequently

    *Generally only one action is allowed per click. Actions include opening a new window, navigating, autoplaying media, etc...