Reputation: 32145
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:
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:
Audio()
element with an alternative and compatible one?How can I manage this?
Upvotes: 0
Views: 154
Reputation: 6746
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;
Upvotes: 1
Reputation: 93
As you mentioned above you can easily check the compatibility, but I think as you can see in the comments this feature is rarely unsupported and there are few old browsers that doesn't support it and the main problem here is the MP3 codec support which you can test it with canPlay()
and you can assure it like this:
var audio=document.createElement("audio");
audio.controls="controls";
//The mp3 source
var mp3Source=document.createElement("source");
mp3Source.src="myFile.mp3";
mp3Source.type="audio/mpeg";
//the ogg source
var oggSource=document.createElement("source");
oggSource.src="myFile.ogg";
oggSource.type="audio/ogg";
//Append the source elements to the audio
audio.appendChild(mp3Source);
audio.appendChild(oggSource);
Your currently used new Audio()
construtor provides access to the properties of <audio>
elements, as well as methods to manipulate them using :
mySound = new Audio([URLString]);
Take a look at MDN HTMLAudioElement Specifications where you can see that the new Audio()
construtor is basically supported by approximately all browsers as you can see below:
Upvotes: 1