How to play background audio on iOs devices’ web pages
This is a horrible hack that works beautifully (’till next Apple iOs update).
It was a while that we where looking for a background audio solution for our Adslife browser game when played on iPad or other iOs devices. Apple’s policy about audio and video autoplay in iOs browser is to deny this feature.
After several failed attempts I figured out a simple hack that makes it possible to call directly the source URL of audio files and play them on the HTML page load.
I first noticed that Safari on iOs plays automatically a mp3 file (or even mp4: videos!) if it is directly called as a URL.
Then, why not include a hidden iframe in the page pointing to the audio file to load and play it once the page and iframe are loaded?
It works!
Once you load the page, just after buffering the mp3, the audio starts playing!
Here is the javascript code:
[sourcecode language=”javascript”]
var isiOs = (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i));
function bgAudio(opt){
if (isiOs){
var ifr=document.createElement("iframe");
ifr.setAttribute(‘src’, opt.mp3);
ifr.setAttribute(‘id’, "bgAudio");
ifr.setAttribute(‘width’, ‘0’);
ifr.setAttribute(‘height’, ‘0’);
ifr.setAttribute(‘scrolling’, ‘no’);
ifr.style.border="0px";
document.body.appendChild(ifr)
} else{
var audio=document.createElement("audio");
audio.setAttribute("id","bgAudio");
var mp3Source= document.createElement("source");
mp3Source.setAttribute(‘src’, opt.mp3);
var oggSource=document.createElement("source");
oggSource.setAttribute(‘src’, opt.ogg);
audio.style.display="none";
audio.appendChild(mp3Source);
audio.appendChild(oggSource);
document.body.appendChild(audio);
audio.load();
audio.volume=0.6;
audio.play();
}
}
window.onload = function() {
bgAudio({mp3:"http://dl.dropbox.com/u/1976976/segreteria.mp3", ogg:"http://dl.dropbox.com/u/1976976/segreteria.ogg"});
};
function stopBgndAudio(){
var el= document.getElementById("bgAudio");
document.body.removeChild(el);
}
[/sourcecode]
And here is a demo page.
Actually I tested it on iOs 4.3.5 but I’m quite sure it works on previous versions too.
This hack does not solve the other limitation imposed by Apple on all iOs devices: Play two audios at once 🙁 .
We can’t have everything in this life…
Hope this is helpful – and that you’ll play Adslife 🙂
Hi Alfred,
using this method to load audio as background you don’t have control of audio events; this is a “terrible” hack that works on iOs devices. If you whant to load background audio on a website only than you can use the AUDIO tag directly with all the events control to play it back once ended.
Bye,
Matteo
is it possible to repeat the music after loading? i.e. loop