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.
But, in this example site it works fine without interacting with the page. How can I make it possible? Thanks in advance.
14 Answers
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:
// 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:
0Try this:
window.audio = new Audio( 'quite-impressed.mp3' )
$('body').on('mouseleave', function(){ audio.play()
})
This worked for me on Chrome 77:
- On address bar: chrome://settings/content/sound
- Turn off "Allow sites to play sound (recommended)"
- Turn it on again
if your js play function is not running and if your code is correct then this may help,you have to allow your browser to get that sound file
just goto settings =>privacy and security => site-settings =>sound. and then add your local url at add to play section..
1