Search code examples
javascriptgoogle-chromeaudio

JavaScript play() function does not working in Chrome


I created an audio object and want to play it when user leave the window. So, my code is here:

$('body').on('mouseleave', function(){
    var audio = new Audio( 'quite-impressed.mp3' )
    audio.play()
})

It works well in Firefox. It also works in Chrome if I click in the page and then leave mouse outside of the body. But, when I leave the mouse without clicking in the page an error showed in the console and the audio does not play

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

But, in this example site it works fine without interacting with the page. How can I make it possible? Thanks in advance.


Solution

  • It seems they use an AudioContext to play that sound.
    Chrome did came back a few months ago about blocking the AudioContext API, because a lot of fair uses were not prepared for such restriction and thus got broken by it.

    But M71, which will get released in December 2018 will reenable that restriction, you can read about it here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

    // this will work in Chrome < 70 but not af
    onmouseout = e => {
      const ctx = new AudioContext();
      const osc = ctx.createOscillator();
      osc.connect(ctx.destination);
      osc.start(0);
      osc.stop(1);
    }
    

    Outsourced live example, since Stacksnippets are always granted the user gesture anyway: https://jsfiddle.net/zy3ev8ka/