How to Detect Whether Video Format Supported using Javascript

javascript
Published on April 23, 2019

All platforms/browsers do not accept all video formats for HTML5 <video> element. Although you can specify multiple <source> elements for a given video, yet sometimes you would like to know whether a given video format can be played back in the given browser or not.

This can be done with the can​Play​Type method on the given <video> element. It takes the MIME type of the video (for example video/mp4) and returns a hint whether the video can be played or not. There can be 3 return values :

  1. "" (empty string) : Video format is not supported and definitely cannot be played.
  2. maybe : Cannot tell whether format is supported wihout downloading some part of the video. May or may not be supported.
  3. probably : Video format is most probably supported and probably can be played. This value obviously represents the best-case scenario.
// best to create a new video element to detect format support
var video_element = document.createElement('video');

// detect whether 'video/mp4' format is supported
// "probably" may be the return value
console.log(video_element.canPlayType('video/mp4'));

// depending on the results you can set the source for the main video player

You can also detect whether a format with a given codec can be played or not. An example of MIME type with codec can be video/mp4; codecs="vc1.42E01E, mp4a.40.2".

// detect whether 'video/mp4; codecs="vc1.42E01E, mp4a.40.2"' MIME type is supported
console.log(video_element.canPlayType('video/mp4; codecs="vc1.42E01E, mp4a.40.2"'));

Specifying the codecs in the MIME type has a better chance of returning probably as you are passing complete information about the MIME type.

In this Tutorial