I am trying to get an audio to play in all possible modern browsers, including ios and android.
I have written a function to play either an ogg or mp3 assuming I have both versions on the server:
audio_template = Handlebars.compile('<audio autoplay>' +
' <source src="{{ src }}.mp3">' +
' <source src="{{ src }}.ogg">' +
'</audio>');
/* No extention--assuming both ogg and mp3 are present. */
function playAudio(src) {
var audio = new Audio();
if (audio.canPlayType('audio/mp3') {
audio.src = src + ".mp3";
}
else {
audio.src = src + ".ogg";
}
audio.play();
}
//plays on desktop browsers, nothing on mobile
function playAudio2(src) {
$('body').append(audio_template({src:src}));
}
//plays on desktop browsers, nothing on mobile
function playAudio3(src) {
var audio = $(audio_template({src:src}));
audio[0].play();
}
This plays successfully in all desktop browsers, but produces nothing on ios safari or android chrome. I tried using the remote debugger provided by the android platform tools (adt), but calling playAudio simply return "undefined" with no errors. So does audio.play(), when I placed a breakpoint before audio.play().
I also tried embedding the output of that handlebars template to the bottom of my body tag and playing it, but that failed as well.
Is it the format that's the problem? Or is it simply a limitation of not being able to play hidden audio elements?