HTML5 Game - Controlling Media Playback via HTMLMediaElement

Introduction

The HTMLMediaElement can control playback and get information about playback.

These properties and methods are described in the following table.

Member Description Returns
currentTime Returns the current playback point in the media file number
durationReturns the total length of the media filenumber
ended Returns true if the media file has finished playing boolean
pause() Pauses playback of the media void
paused Returns true if playback is paused; returns false otherwise boolean
play() Starts playback of the media void

The following table shows how you can use the properties in the table to get information about playback.

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;}  
            div {clear: both;}  
        </style>  
    </head>  
    <body>  
        <video id="media" controls width="360" height="240" preload="metadata">  
            <source src="your.webm"/>  
            <source src="your.ogv"/>  
            <source src="your.mp4"/>  
            Video cannot be displayed  //  w w  w . j a  v a2 s .co m
        </video>  
        <table id="info" border="1">  
            <tr><th>Property</th><th>Value</th></tr>  
        </table>  
        <div>  
            <button id="pressme">Press Me</button>  
        </div>  
        <script>  
            let mediaElem = document.getElementById("media");  
            let tableElem = document.getElementById("info");  
              
            document.getElementById("pressme").onclick = displayValues;  
              
            displayValues();  
              
            function displayValues() {  
                let propertyNames = ["currentTime", "duration", "paused", "ended"];  
                tableElem.innerHTML = "";  
                for (let i = 0; i < propertyNames.length; i++) {  
                    tableElem.innerHTML +=  
                        "<tr><td>" + propertyNames[i] + "</td><td>" +  
                        mediaElem[propertyNames[i]] + "</td></tr>";  
                }  
            }  
        </script>  
    </body>  
</html>

Related Topic