Wednesday, March 23, 2016

Autoplay sound in chrome background tab

Leave a Comment

So I have a HTML5 game that uses audio notifications.

When users are searching for other players with match-making they frequently change tabs to do other things and rely on the audio notification to know when to come back. This no longer works after Chrome changed to disallow audio notifications.

How can I ensure it still works?

2 Answers

Answers 1

Here is an example that creates a div and uses HTML5 <audio> tag with a fallback to <embed> that plays an audio file 3 seconds after clicking the button.

To test it, run the sample and click the button, then change tabs and count 3 seconds. You should see the speaker icon on this tab and hear the coin drop sound after 3 seconds even though this tab is not the current tab.

function playCoinDrop() {    soundDiv = document.createElement("div");    soundDiv.innerHTML = '<audio autoplay="autoplay"><source src="http://themushroomkingdom.net/sounds/wav/smw/smw_coin.wav" type="audio/wav" /><embed hidden="true" autostart="true" loop="false" src="http://themushroomkingdom.net/sounds/wav/smw/smw_coin.wav" /></audio>';  }
<button onclick="setTimeout(playCoinDrop, 3000)">play sound</butotn>

You can replace the audio file as you see fit.

Answers 2

Here, background tabs still can play sounds from <audio> elements (Chrome 49.0.2623.87). However, if Chrome blocked this, a way to work around it would be to notify the front tab of an event and have it play the sound instead of the background tab.

The following would need to be implemented as a userscript extension so that it could work on any tab - as a demo, it works just between two tabs with the same JSBin URL:

var intercom = Intercom.getInstance();  document.addEventListener("visibilitychange", getVisible);  function getVisible (evt) {   document.getElementById("fg-indicate").style.visibility = document.visibilityState;   if (document.visibilityState == "visible") {          // tab comes to front => listen to intercom      intercom.on('notice', play);    } else {      // kill callback      intercom.off('notice', play);      // call intercom with delay      window.setTimeout(function f() {        intercom.emit('notice', {message: 'Hello, all windows!'});      }, 3000);    } }  function play() {   document.getElementsByTagName("audio")[0].play(); } 

It relies on the intercom.js library and uses localstorage to communicate between open tabs.

Try this out by

and so on.

The code and a bit more code to inject an <audio> element could be wrapped in a userscript so it can run on any site that happens to be in front.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment