How to play sounds / music cross browser including IE - Ideal for HTML5 canvas games
This will work, even in IE11! First make sure you have an old fashioned bgsound tag somewhere in your html document body.
<bgsound id="sound">
Next, place the following function into your javascript file:
function playSomeSounds(soundPath)
{
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
document.all.sound.src = soundPath;
}
else
{
var snd = new Audio(soundPath); // buffers automatically when created
snd.play();
}
};
Ok so now you can call this function at any time and just pass through the sound path:
playSomeSounds("sounds/welcome.wav");
I haven't tried other music file types with this solution but although wav files are uncompressed, they do offer the most compatability rather than having to deal with several versions all at the same time. If you have a preloader for your game, then what's the big deal? Of course, it's all within reason. If you're wav file is like 16mb, then you might need to look at cutting that down a bit.
Leave a comment
Need help with this article?
Have you got a suggestion, compliment or need additional help with this article? Simply contact me at ajfhoward[@t]hotmail.com and I'll try to help as much as I can.