Of course I have a backup!

Random blobs of wisdom about software development

The state of HTML5 audio

Friday, October 12, 2012

I just had a chance to use the "new" HTML5 <audio> tag. Using it is just as eas y as using anything from HTML5/CSS3. That was sarcasm. The same things apply, you need to be aware of all the various browser inconsis tencies. The main one is the supported formats of course, some vendors support the industry standard MP3, others don't want to support that because it's not open, and Google supports everything because they are swimming in money, and can afford it. Turns out that in o rder to support all the browsers out there, you need to offer at least 2 kinds of formats, consult the chart on Wikipedia for details. While that's inconvinient, like most things in the CSS3/HTML5 area, there is a much bigger waitwhat? here.

What do all the tutorials on javascript say about doing user agent sniffing? Don't do it. Detect if the browser can do what you want it to do, and act according to that. Alright, let's see, is there a way to check if a browser can play back an audio format? Yes, there is canPlayType() , great! Using it is easy:

var audio = new Audio();
if (audio.canPlayType('audio/wav')) {
    // Rejoice!
} else {
    // Try the next one

Haha, no, I lied. The above fragment would be 100% logical, but canPlayType() does not return a boolean. Do you know what it returns? CanPlayType returns one of three values:

  • probably
  • maybe, or
  • “” (the empty string).

Wait, what?

It returns probably? Maybe? There isn't even a yes?? According to html5doctor.com, the reason for this is:

The reason we have these odd return types is because of the general weirdness surrounding codecs. The browser can only guess at whether a certain codec is playable without actually trying to play it.

So, after coming back together from the surprise, here is an actual way of testing if the browser maybe supports a format:

var audio = new Audio();
var canPlayOgg = !!audio.canPlayType && audio.canPlayType('audio/ogg; codecs="vorbis"') != ""

First, we check if the browser supports the canPlayType method on the Audio object, then we check if that returns anything other than an empty string. Welcome to HTML5.

This was written by Norbert Kéri, posted on Friday, October 12, 2012, at 22:07

Tagged as:
Andy wrote
You can use canPlayType() like a boolean if you're not concerned about the distinction between "maybe" and "probably"; the empty string response evaluates as a False value in an if condition.

2013-05-03 05:14:56

Post a comment

Providing your email is optional, it is never published or shared, it is only used for auto approval purposes. If you already have at least 1 approved comment(s) tied to your email, you don't have to wait for moderation, otherwise the author must approve your comment.

Please solve this totally random captcha