media API. Control video from JavaScript

Along with the new audio and video elements in HTML5, a new JavaScript API has been added to manipulate these elements. With JavaScript code, we can get the video and audio elements (just like any other element) and use their properties. In JavaScript, these elements are represented by the HTMLMediaElement object , which allows you to control audio and video playback using properties, methods, and events. Let’s note the most important properties that we can use to customize these elements:

  • playbackRate : sets the playback speed. Default is 1
  • src : returns the name of the resource being played if it is set in the element’s html code
  • duration : returns the duration of the file in seconds
  • buffered : returns the duration of the part of the file that is already buffered and ready to be played
  • controls : Sets or returns the presence of the attribute controls. If it is set, returns true, otherwise returnsfalse
  • loop : Sets or returns the presence of the attribute loop. If it is set, returns true, otherwise returnsfalse
  • muted : Sets or returns the presence of an attributemuted
  • preload : sets or returns the presence of an attributepreload
  • volume : Sets or returns the volume level from 0.0 to 1.0
  • currentTime : returns the current playing time

Separately, for an element, video we can use a number of additional properties:

  • poster : sets or returns an attributeposter
  • height : sets or returns an attributeheight
  • width : sets or returns an attributewidth
  • videoWidth, videoHeight : for the video element, return the width and height of the video

We should also note two methods by which we can control playback:

  • play() : starts playing
  • pause() : pause playback

The main events of the video and audio elements are:

  • canplaythrough : This event fires after the page has loaded if the browser determines that it can play this video/audio
  • pause : The event is fired when media playback is paused and it is put into the “paused” state
  • play : the event fires when the file starts playing
  • volumechange : Fires when the media volume changes
  • ended : fires when playback ends
  • timeupdate : fired when the play time changes
  • error : generated when an error occurs
  • loadeddata : fired when the first frame of the video file is loaded
  • loadedmetadata : Fires after media metadata is loaded (play time, video dimensions, etc.)
  • seeking : fired when the user starts moving the cursor on the playline to move to a new location in the audio or video file
  • sought : fired when the user has completed moving to a new location on the playline

Now let’s use some of these properties, events, and methods to manipulate the video element:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio in HTML5</title>
    <style>
        .hidden {
            display: none;
        }

        #playBtn {
            border: solid 1px #333;
            padding: 5px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <video width="400" height="300">
        <source src="mov_bbb.mp4" type="video/mp4">
        <source src="mov_bbb.webm" type="video/webm">
        <source src="mov_bbb.ogv" type="video/ogg">
    </video>
    <div id="controls" class="hidden">
        <a id="playBtn">Play</a>
        <span id="timer">00:00</span>
        <input type="range" step="0.1" min="0" max="1" value="0" id="volume" />
    </div>
    <script>

        // get all elements
        var videoEl = document.getElementsByTagName('video')[0],
            playBtn = document.getElementById('playBtn'),
            vidControls = document.getElementById('controls'),
            volumeControl = document.getElementById('volume'),
            timePicker = document.getElementById('timer');

        // if the browser can play the video, remove the class
        videoEl.addEventListener('canplaythrough', function () {
            vidControls.classList.remove('hidden');
            videoEl.volume = volumeControl.value;
        }, false);
        // start or stop playback
        playBtn.addEventListener('click', function () {
            if (videoEl.paused) {
                videoEl.play();
            } else {
                videoEl.pause();
            }
        }, false);

        videoEl.addEventListener('play', function () {

            playBtn.innerText = "Pause";
        }, false);

        videoEl.addEventListener('pause', function () {

            playBtn.innerText = "Play";
        }, false);

        volumeControl.addEventListener('input', function () {

            videoEl.volume = volumeControl.value;
        }, false);

        videoEl.addEventListener('ended', function () {
            videoEl.currentTime = 0;
        }, false);

        videoEl.addEventListener('timeupdate', function () {
            timePicker.innerHTML = secondsToTime(videoEl.currentTime);
        }, false);

        // display time calculation
        function secondsToTime(time) {

            var h = Math.floor(time / (60 * 60)),
                dm = time % (60 * 60),
                m = Math.floor(dm / 60),
                ds = dm % 60,
                s = Math.ceil(ds);
            if (s === 60) {
                s = 0;
                m = m + 1;
            }
            if (s < 10) {
                s = '0' + s;
            }
            if (m === 60) {
                m = 0;
                h = h + 1;
            }
            if (m < 10) {
                m = '0' + m;
            }
            if (h === 0) {
                fulltime = m + ':' + s;
            } else {
                fulltime = h + ':' + m + ':' + s;
            }
            return fulltime;
        }
    </script>
</body>

</html>

First, in the JavaScript code, we get all the elements. Then, if the browser supports the video and can play it, we handle the event canplaythroughby setting the audio level and removing the hidden class:

videoEl.addEventListener('canplaythrough', function () {
    vidControls.classList.remove('hidden');
    videoEl.volume = volumeControl.value;
}, false);

To start playback, we need to handle clicking the Play link:
 
playBtn.addEventListener('click', function () {
    if (videoEl.paused) {  // if the video is stopped/start
        videoEl.play();
    } else {
        videoEl.pause();
    }
}, false);

By handling playback start and stop events, we can change the caption on the link:

 
videoEl.addEventListener('play', function () {
        
    playBtn.innerText = "Pause";
}, false);
        
videoEl.addEventListener('pause', function () {
        
    playBtn.innerText = "Play";
}, false);

By handling the event input that is fired when the slider value changes, we can synchronize the change in the slider and the volume of the video:

volumeControl.addEventListener('input', function () {
        
    videoEl.volume = volumeControl.value;
}, false);

Handling the event endedwill reset the playback time:

videoEl.addEventListener('ended', function () {
    
    videoEl.currentTime = 0;
}, false);

And the event handler timeupdatewill allow you to dynamically change the playback time indicator:

 
videoEl.addEventListener('timeupdate', function () {
    timePicker.innerHTML = secondsToTime(videoEl.currentTime);
}, false);

A helper function is used to format the time string secondsToTime.

Well, in a similar way, you can add other elements, for example, a playback scale, some other buttons.