How to detect supported video formats for the HTML5 video tag?

笑着哭i 提交于 2019-11-27 00:53:01
Will

You can check codecs for different video types with HTMLVideoElement.prototype.canPlayType. There is also a great HTML5 feature detection library, Modernizr.

var testEl = document.createElement( "video" ),
    mpeg4, h264, ogg, webm;
if ( testEl.canPlayType ) {
    // Check for MPEG-4 support
    mpeg4 = "" !== testEl.canPlayType( 'video/mp4; codecs="mp4v.20.8"' );

    // Check for h264 support
    h264 = "" !== ( testEl.canPlayType( 'video/mp4; codecs="avc1.42E01E"' )
        || testEl.canPlayType( 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' ) );

    // Check for Ogg support
    ogg = "" !== testEl.canPlayType( 'video/ogg; codecs="theora"' );

    // Check for Webm support
    webm = "" !== testEl.canPlayType( 'video/webm; codecs="vp8, vorbis"' );
}

I'd recommend you use something like http://videojs.com/, they use a Flash fallback and their syntax will give you the correct order of the formats that you should use for all browsers.

It goes like this:

<a href="http://video-js.zencoder.com/oceans-clip.mp4">MP4</a>,
<a href="http://video-js.zencoder.com/oceans-clip.webm">WebM</a>,
<a href="http://video-js.zencoder.com/oceans-clip.ogv">Ogg</a>

If the browser doesn't understand MP4, it goes to WebM, if it doesn't it goes to OGG, if it doesn't understand it, it goes to the Flash fallback.

Think of it like font-family declarations in CSS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!