I have an 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
Here is an example that creates a div and uses HTML5 tag with a fallback to
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 = '';
}
You can replace the audio file as you see fit.
Here is a more advanced way that utilizes localStorage
which will probably be your best option. This allows you to preload the notification sound by downloading it into localStorage as Base64 and then you can invoke playing it when the tab is in the background without causing additional network transfers.
A major benefit to this approach is that there is only one download of the notification file, and then after that it is played locally from the browsers localStorage.
downloadCoin()
function stores the file in localStoarge
as base64
playCoinDrop()
creates a div on the fly and plays the base64 data
playCoinDropJS()
plays the base64 data without creating any div
function downloadCoin() {
var coin = 'smw_coin.wav';
var xhr = new XMLHttpRequest();
xhr.open('GET', coin, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = new Blob([this.response], {
type: 'audio/wav'
});
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var coinB64 = reader.result;
var myStorage = localStorage.setItem('coin_base64', coinB64)
}
}
};
xhr.send();
}
function playCoinDrop() {
var coinB64 = localStorage.getItem('coin_base64');
var soundDiv = document.createElement('div');
soundDiv.innerHTML = '
demo on github