Detect if browser can play html5 media format with JavaScript

I love the concept of Modernizr, but when you can do something simple with a couple of lines of JavaScript without loading another library, you probably should.

Say, for example that I want to display a video with HTML5’s <video> tag, but I need to detect wether my browser supports MP4 or Theora.Ogg. You can do it easily with the canPlayType() method. You can simple create a new media element and then use the canPlayType to check for the proper format support.

var myVideo = document.createElement('video');

if (myVideo.canPlayType('video/mp4')) {
    vidExt='.m4v';
}

if (myVideo.canPlayType('video/ogg')) {
    vidExt='.ogg.theora';
}

This will create a variable called vidExt and place in it the extension to be used when loading a video. So if you wanted to load the video into a container with an id of media as in

<div id="media"></div>

Then you can simply use this in your Javascript file.

document.getElementById('media').appendChild(myVideo);
myVideo.src="BikerWriting"+vidExt;
myVideo.setAttribute("controls","controls");
myVideo.play();

Now the video with the proper extension will play. Here’s the completed code for a simply JavaScript player that will play video in either mp4 or theora.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div id="media"></div>
<script>
    var myVideo = document.createElement('video');

    if (myVideo.canPlayType('video/mp4')) {
        vidExt='.m4v';
    }

    if (myVideo.canPlayType('video/ogg')) {
        vidExt='.ogg.theora';
    }

    document.getElementById('media').appendChild(myVideo);
    myVideo.src="BikerWriting"+vidExt;
    myVideo.setAttribute("controls","controls");
    myVideo.play();

</script>
</body>
</html>

This assumes that you’ve saved both versions with the same name ‘BikerWriting’, they’re in the same folder and have different extensions (.m4v for mp4 and .ogg.theora for theora video).

If you need to compress the video, the best way is to download the free open source miro video converter. For audio, try media.io. Here’s media types you can use for canPlayType.

  • video/mp4 – .h264 Video
  • video/ogg – Ogg Theora Video
  • video/webm – WebM Video
  • audio/mpeg – MP3 Audio
  • audio/ogg – OGG Audio

Leave a Reply

Your email address will not be published. Required fields are marked *