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:
var audio = new Audio();
if(audio.canPlayType("audio/mpeg") == "probably") {
playSound("myMedia.mp3");
} else if(audio.canPlayType("audio/webm") == "probably") {
playSound("myMedia.webm");
}
// do checks for other types...
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:
<audio controls="controls">
<source src="mymedia.ogg" type="audio/ogg" />
<source src="mymedia.mp3" type="audio/mpeg" />
Update your browser! This sentence is fallback content for browsers that do not support the audio element at all.
</audio>
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:
audio.canPlayType('audio/ogg; codecs="vorbis"') == "probably";
Note that canPlayType
has three possible return values:
- "probably" - the media type can almost certainly be played
- "maybe" - the media type might be playable. This is what is returned when you ask about general Ogg support in a browser has Ogg support for specific codecs (i.e. Vorbis and Theora). An Ogg file may use a codec that is not supported by the browser, so if you don't specify the codec, the browser can only guess that it might be able to play it.
- "" (the empty string) - the media type is certainly not playable
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:
// test for *any* Ogg codecs
if(audio.canPlayType("audio/ogg") != "") {
playSound("myMedia.ogg");
}
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.
canPlayType
: developer.mozilla.org/en-US/docs/DOM/HTMLMediaElement#Methods – Metchnikoff