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 🙂