Search code examples
javascripthtmlaudiocompatibility

How can we make audio works in all browsers, what primitive can we use if a browser doesn't support it?


Well I am writing a web application using JavaScript and HTML5 and I have to put a sound notification in my web page, this is how I am calling it in JavaScript:

sounds: {
    bip: new Audio('/sounds/bip.mp3') 
}

But I want to make sure that this audio works in all browsers. So I have two questions:

  1. How can I check if the audio works in all browsers?

I saw all the answers here and I also found solutions here:

So there was an answer for this question:

var test_audio= document.createElement("audio"); //try and create sample audio element
var audiosupport=(test_audio.play)? true : false;

But my problem now is:

  1. How can I make sure that the audio will always play in all browsers? How can I replace the Audio() element with an alternative and compatible one?

How can I manage this?


Solution

  • You need this as an alternative for browsers that do not support audio element

    <object data="/sounds/bip.mp3" >
    <param name="src" value="/sounds/bip.mp3"/>
    </object>
    

    With JavaScript you could use something like this:

    var obj = document.createElement('object'), 
        param = document.createElement('param');
    
    param.name = "src";
    param.value = "/sounds/bip.mp3";
    
    obj.appendChild(param);
    document.body.appendChild(obj);
    

    You can check wether to use this or notusing Modernizr or with your code (have not tested):

    var test_audio= document.createElement("audio"); //try and create sample audio element
    var audiosupport=(test_audio.play)? true : false;