I'm using this function:
function playSound(file) {
MyAudio = new Audio(file);
MyAudio.play();
}
Unfortunately, I'm struggling to find a file type which will work in all browsers. Mp3 works in Chrome, Safari, IE but not FF and Opera, while .ogg files only seem to work in FF.
Any suggestions as to a way around this? I presume there is no way of programmatically detecting which browser is being used and then playing the appropriate file type? Any advise/ideas appreciated. Thanks.
Frustratingly, there is no universally playable type. WAV comes closest, but it is quite large and is not supported in IE9. You'll need to have multiple types available and choose a type the browser can play.
To do this, use feature detection, not browser detection. The media types that each browser supports will change over time, so your code that assumes Firefox can't play MP3 will probably be outdated a few years from now, when Mozilla adopts it (after the patents expire). Use canPlayType, which indicates if a given format is supported:
Also, if you are writing the audio tag as HTML, you can use multiple
<source>
tags, and the browser will play the first one it can:If you want to test for Ogg audio support, you probably want to test for Ogg Vorbis specifically. Ogg is a "container" format that can hypothetically use other codecs besides Vorbis and Theora (for example, the Opus format). You can test for Ogg Vorbis like so:
Note that
canPlayType
has three possible return values:If you really wanted to test for ogg support, then instead of testing for "probably", you could test for a non-empty string (i.e., test for either "probably" or "maybe"), like so:
You should test for whatever specific codec your media file uses, e.g., with
'audio/ogg; codecs="vorbis"'
for Vorbis. Testing for general Ogg support is not likely to be useful.Use webm for Chrome, Firefox and Opera + wav for Firefox, IE, Safari and Opera.
HTML:
JS:
To explain:
Javascript find out users browser and if it is Chrome it serves
webm
and if it is not than it usewav
Note: Using this code you need only both
webm
andwav
audio with same name inaudio
folder.Note 2: Code needs jQuery.
Well, see here: jQuery Buzz extension. Never used it, but heard it should work fine. It's able to check if your browser supports some format, really neat feature.