Customizing controls for media elements

Media elements, currently video and audio, can be controlled using JavaScript since the elements theme self contain useful methods and attributes. In this recipe, we will go through some of the most basic functionality and methods that can be applied on elements that have the HTMLMediaElement interface.

Note

Specification on the HTML5 media element can be found at http://www.w3.org/TR/html5/embedded-content-0.html#htmlmediaelement.

Getting ready

In this recipe we will also need a video file, so we can use the same one from the previous recipe.

How to do it...

We start by creating a JavaScript controller that will have very rudimentary functionality of a media player.

  1. Our controller methods will accept a selector for a command and execute the command, we need the following:
    var videoController = (function () {
      var my = {};
      function findElement(selector){
       var result = document.querySelector(selector);
       if (!result) {
        throw "element " + selector + " not found ";
       }
       return result;
      }
    
      function updatePlaybackRate(el, speed) {
       el.playbackRate += speed;
      }
    
      function updateVolume(el, amount) {
       el.volume += amount;
      }
    
      my.play = function(video) {
       var el = findElement(video);
       el.play();
      }
    
      my.pause = function(video) {
       var el = findElement(video);
       el.pause();
      }
    
      my.toggleMute = function(video) {
       var el = findElement(video);
        el.muted = !el.muted;
      }
    
      my.increasePlaybackRate = function(video, speed) {
       var el = findElement(video);
       updatePlaybackRate(el, speed);
      }
    
      my.decreasePlaybackRate = function(video, speed) {
       var el = findElement(video);
       updatePlaybackRate(el, -speed);
      }
    
      my.increaseVolume = function(video, amount) {
       var el = findElement(video);
       updateVolume(el, amount)
      }
      return my;
    }());

    Now in a simple scenario we probably could just use the standard methods without adding another layer, but the idea here is that we can extend the functionally as we see fit since we have accessible element from JavaScript.

  2. For the HTML we shall have a similar version to the one in the playing videos recipe. We will have a few buttons that will use our video controller and additionally add a simple style. Let's add the following to the head section:
      <head>
        <title>Video custom controls</title>
        <style>
          video {
            box-shadow: 0 0 10px #11b;
          }
        </style>
      </head>
  3. The body part will contain the control buttons:
        <p>
          <video id="theVideo" width="640" height="480" poster="poster.png" preload loop>
              Video playback not supported <a href="http://archive.org/download/WalterLantz-BoogieWoogieBugleBoy1941/WalterLantz-BoogieWoogieBugleBoy1941.ogv"> download </a>
            <source src="http://archive.org/download/WalterLantz-BoogieWoogieBugleBoy1941/WalterLantz-BoogieWoogieBugleBoy1941.ogv" type="video/ogg" />
          </video>
        </body>
        <p>
        The Dashboard: <br/>
          <button onclick="videoController.play('#theVideo')">Play</button>
          <button onclick="videoController.pause('#theVideo')">Pause</button>
          <button onclick="videoController.increasePlaybackRate('#theVideo',0.1)">Speed++</button>
          <button onclick="videoController.decreasePlaybackRate('#theVideo',0.1)">Speed-- </button>
          <button onclick="videoController.decreaseVolume('#theVideo', 0.2) ">Vol-</button>
          <button onclick="videoController.increaseVolume('#theVideo', 0.2) ">Vol+</button>
          <button onclick="videoController.toggleMute('#theVideo')">Toggle Mute</button>
        <p>
        Video is part of animation shorts on <a href="http://archive.org/details/more_animation"> archive.org</a>. The video
        is titled : Walter Lantz - Boogie Woogie Bugle Boy
        </p>
  4. And we add the dependencies to our example.js file.
    <script src="example.js"> </script>

After that we should have a fully running video player.

How it works...

With JavaScript we can access and manipulate the attributes of any media element. This option enable us to do many different types of customization on the standard elements. Most of these properties are defined in HTMLMediaElement; there we can read and write to the currentTime, playbackRate, volume, muted, defaultMuted, and so on.

Note

For a more comprehensive list HTMLMediaElement attributes and what is read only please refer to the specification available at http://www.w3.org/TR/html5/embedded-content-0.html#media-elements.

By changing attributes we can make custom players but also various different visual updates. There are large amount of different events that get trigger by media elements. On the events we can attach event listeners and make updates depending on the state change. The following events get triggered: loadstart, abort, canplay, canplaythrough, durationchange, emptied, ended, error, loadeddata, loadedmetadata, pause, play, playing, progress, ratechange, seeked, seeking, stalled, suspend, timeupdate, volumechange, and waiting.

Note

The name of the events are self-explanatory, if you are interested into more details about a specific event you can read up what they are intended for, in the documentation at http://www.w3.org/TR/html5/embedded-content-0.html#mediaevents.

In our example we could add a listener to the rate speed that will display the current rate:

  my.displayRate = function (video, output) {
   var vid = findElement(video),
       out = findElement(output);

   vid.addEventListener('ratechange', function(e) {
     console.log(e);
     out.innerHTML = 'Speed x' + this.playbackRate;
   }, false);
  }

And then add an output element in the HTML with a call to our newly added method:

    <output id="speed"></output>
    <script>
      videoController.displayRate("#theVideo","#speed");
    </script>

Now the first time the video is played the rate change event get's triggered and the rate is set to 1. Every consecutive rate change will trigger the same event.

Note

W3C has a a great demo on events triggered by media elements at http://www.w3.org/2010/05/video/mediaevents.html.

One other interesting thing to note here is that <audio> element can be used on video files as well, but only the audio stream from the files will be played.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.74.25