Detect Supported Audio Formats with JavaScript

As streaming becomes our main entertainment source and vendors fight to create the best video format, it's going to be more and more important that we detect device and browser video support before posting videos on our websites. We think less about audio but the same principle applies: detect whether or not a given audio format is supported before using it. So how do we detect if a given audio type is supported?

We can detect audio format support with HTMLAudioElement.prototype.canPlayType, the same strategy that's used with video:

// Create an audio element so we can use the canPlayType method
const audio = document.createElement('audio');
// Does the device support mp3?
audio.canPlayType('audio/mpeg'); // "probably"

There are three possible results from canPlayType:

"probably" : The media type appears to be playable

"maybe": Cannot tell if the media type is playable without playing it

"": The media type is not playable

We can create a function much like my supportsVideoType function to make audio detection easy:

Taking the time to detect edge audio and video formats is well worth it, allowing you to deliver clearer media with better compression to improve load time. Keep these JavaScript functions in mind for your large or small media site!

I was inspired when I first saw Addy Osmani's original ShineTime blog post. The hover sheen effect is simple but awesome. When I started my blog redesign, I really wanted to use a sheen effect with my logo. Using two HTML elements and...

While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready? Promises are becoming a big part of the JavaScript world...

Honesty hour confession: file uploading within the web browser sucks. It just does. Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms. Add to those criticism the fact that we're all used to drag and drop operations...

I was recently redesigning my website and wanted to create tooltips. Making that was easy but I also wanted my tooltips to feature the a triangular pointer. I'm a disaster when it comes to images and the prospect of needing to make an image for...

Continue this conversation via emailGet only replies to your comment, the best of the rest, as well as a daily recap of all comments on this post. No more than a few emails daily, which you can reply to/unsubscribe from directly from your inbox.