HTML5 Game - Assessing Playback Capabilities for video element

Introduction

The canPlayType method from HTMLMediaElement can get an idea of whether the browser can play a particular media format.

This method returns one of the values shown in the following table.

Value Description
"" (empty string) The browser cannot play the media type.
maybe The browser might be able to play the media type.
probably The browser is reasonably confident that it can play the media type.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            table {border: thin solid black; border-collapse: collapse;}
            th, td {padding: 3px 4px;}
            body > * {float: left; margin: 2px;}
        </style>
    </head>
    <body>
        <video id="media" controls width="360" height="240" preload="metadata">
            Video cannot be displayed//from  w  ww  .  j  av a  2s  . co m
        </video>
        <table id="info" border="1">
            <tr><th>Property</th><th>Value</th></tr>
        </table>
        <script>
            let mediaElem = document.getElementById("media");
            let tableElem = document.getElementById("info");

            let mediaFiles = ["http://java2s.com/style/demo/your.webm", "http://java2s.com/style/demo/your.ogv", "http://java2s.com/style/demo/your.mp4"];
            let mediaTypes = ["video/webm", "video/ogv", "video/mp4"];
            
            for (let i = 0; i < mediaTypes.length; i++) {
                let playable = mediaElem.canPlayType(mediaTypes[i]);
                if (!playable) {
                    playable = "no";
                }
                
                tableElem.innerHTML +=
                    "<tr><td>" + mediaTypes[i] + "</td><td>" + playable + "</td></tr>";
                    
                if (playable == "probably") {
                    mediaElem.src = mediaFiles[i];
                }
            }
        </script>
    </body>
</html>

Related Topic