js-background-audio
Example of how to play notification sounds in the background using javascript.
Step 1. Download sound file to localStorage:
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();
}
Try it:
Step 2: Play Sound file from localStorage:
function playCoinDropJS(){
var coinB64 = localStorage.getItem("coin_base64");
var snd = new Audio(coinB64);
snd.play();
}
Try it:
Alternative: Create div on the fly and use it to play the sound file from localStorage:
function playCoinDrop() {
var soundDiv = document.createElement("div");
var coinB64 = localStorage.getItem("coin_base64");
soundDiv.innerHTML = '<audio autoplay="autoplay"><source src="' + coinB64 + '" type="audio/wav" />';
}
Try it:
// Tim PENNER