Book Image

HTML5 Video How-To

By : Alex Libby
Book Image

HTML5 Video How-To

By: Alex Libby

Overview of this book

<p>Publishing videos online has been around for a number of years, although has really taken off with the advent of video sharing sites such as YouTube. The power of video is huge if done well; it can present a lot of information in a more visually engaging manner than using written text and pictures. Done badly though – it can present real problems to the company or individual hosting the video, that have the potential to cause some real harm!<br /><br />"HTML5 Video How-To" is a practical, hands-on guide that provides you with a number of clear step-by-step exercises, which will help you take advantage of the real power that is behind HTML5 video, and give you a good grounding in using it in your web pages.<br /><br />This book looks at the HTML5 video formats available, and breaks down the mystery and confusion that surrounds which format to use. It will take you through a number of clear, practical recipes that will help you to take advantage of the new HTML5 video standard, quickly and painlessly. <br /><br />You will also learn how to build your own video player using jQuery, or by using one of the pre-built libraries available. We will also take a look at adding functionality such as lightbox effects, or subtitles, as well as how to publish videos to popular hosting sites, such as YouTube or VideoBin. If you want to take advantage of using the new HTML5 video format, then this is the book for you.<br /><br />You will learn everything you need to know to convert videos into the right format, as well as how to display them in your browser or web pages, across multiple platforms.</p>
Table of Contents (8 chapters)

Adding the jQuery functionality (must know)


So far, we've focused on providing some basic controls, and have added a set of rudimentary styles—as you've already seen from the screenshot, it doesn't look pretty, but it serves a functional purpose. We will develop this into a basic theme, but before doing this, we need to finish adding the jQuery functionality that will make the player work—this is the subject of this next task.

Getting ready

We need to retrieve a copy of the videoplayer.js file that we created earlier, so go ahead and load this into your normal text editor. Other than this, there isn't anything else required—we will add the necessary code as part of the task. I will assume that you're still using the files from previous demos—if this is not the case then please alter this accordingly.

Note

Throughout this section, it is assumed you have some familiarity with creating jQuery plugins—if you want to delve into this more, then you may like to take a look at another Packt book, jQuery Plugin Development Beginner's Guide, by Giulio Bai.

How to do it...

  1. The first change you need to make is in the <header> section of videoplayer.html—go ahead and add in this:

    <script type="text/javascript" 
      src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript"
      src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/
      jquery-ui.min.js"></script>
  2. In our plugin file, videoplayer.js, we need to add in a number of variables that are required for controlling various different elements of the player, so go and add in the following code:

    (function($) {
        $.fn.oPlayer = function(options) {
             return this.each(function() {
                // variables
                var $oMain = $(this);
                var $oVideo = $('video', $oMain);
                var $oPlay = $('.play', $oMain);
                var $oPause = $('.pause', $oMain);
                var $oTimeSlider = $('.time_slider', $oMain);
                var $oTimer = $('.timer', $oMain);
                var $oVolSlider = $('.volume_slider', $oMain);
                var $oMute = $('.mute', $oMain);
                var $oUnmute = $('.unmute', $oMain);
                var $oOverlay = $('.video-overlay', $oMain);
                var bTimeSlide = false;
                var iVolume = 1;
                var $oDuration = $('.duration', $oMain);   
            });
        };
    })(jQuery);
  3. We now need to add in a function that will prepare the volume control, ready to display it on screen, so add in the following code snippet immediately below the last variable from the previous step:

    var prepareTimeSlider = function() {
       if (! $oVideo[0].readyState) {
       setTimeout(prepareTimeSlider, 1000);
       } else {
       $oTimeSlider.slider({
          value: 0,
             step: 0.01,
          orientation: 'horizontal',
             range: 'min',
          max: $oVideo[0].duration,
          animate: true,
          slide: function() {
                bTimeSlide = true;
             },
             stop:function(e, ui) {
             bTimeSlide = false;
             $oVideo[0].currentTime = ui.value;
             }
          });
       };
    };
  4. Now that the basics are in place, let's turn our focus to making the controls work. We'll start with the most important, which are the play and pause buttons, so go ahead and add in this code:

    $oPlay.click(function () {  
       $oVideo[0].play();
       $oPlay.hide();
       $oPause.css('display', 'block');
       $oOverlay.fadeOut();                  
    });
    $oPause.click(function () { 
       $oVideo[0].pause();
       $oPause.hide();
       $oPlay.css('display', 'block');
       $oOverlay.fadeIn();
    });
  5. The next two options will control the sound—here's the code for muting and un-muting the video:

    $oMute.click(function () {  
      $oVideo[0].muted = true;
      $oVolSlider.slider('value', '0');
      $oMute.hide();
      $oUnmute.css('display', 'block');
    });
    $oUnmute.click(function () {  
      $oVideo[0].muted = false;
      $oVolSlider.slider('value', iVolume);
      $oUnmute.hide();
      $oMute.css('display', 'block');
    });
  6. Your users will expect to be able to click on the video to pause and play it at will—let's fix that by adding in a function to cover this:

    $oVideo.click(function () {
      if($oVideo[0].paused) {
        $oPlay.click();
      } else {
      $oPause.click();
      }
      return false;
    });
  7. The basic player will now work perfectly OK, although there will be elements that won't function at all—one of these will be the right-click context menu. Let's fix that now, starting with the play option:

    $oVideo.on("play", function() {
      $oPlay.click();
    });

    then continuing with the pause option:

    $oVideo.on("pause", function() {
       $oPause.click();
    });
  8. This next function will rectify another element that is not quite right—when the video finishes, we need to reset the controls back to play, so that the next person can start the video:

    $oVideo.bind('ended', function() {
       $oVideo[0].pause();
       $oPause.hide();
       $oPlay.css('display', 'block');
    });
  9. Our next function takes care of updating the time controls on the player:

    $oVideo.bind('timeupdate', function() {
      var iNow = $oVideo[0].currentTime;
      $oTimer.text(rectime(iNow));
      if (! bTimeSlide)
      $oTimeSlider.slider('value', iNow);
    });
  10. We do need to know how long the video will be, so let's add in the code that will display this on screen:

    $oVideo.on("canplay", function() {
      $oDuration.text(rectime($oVideo[0].duration));
    });
  11. While we now have the ability to turn the volume on or off, it will make for a better experience if we can provide finer control, so let's add that in now:

    $oVolSlider.slider({
      value: 1,
      orientation: 'vertical',
      range: 'min',
      max: 1,
      step: 0.02,
      animate: true,
      slide: function(e, ui) {
        $oVideo[0].muted = false;
        iVolume = ui.value;
        $oVideo[0].volume = ui.value;
      }
    });
  12. Finally, we need to initialize the Time slider, and remove the default controls that show:

    prepareTimeSlider();
    $oVideo.removeAttr('controls');

    Putting this all together should result in something similar to the following screenshot:

How it works...

Throughout this task, we've worked stage by stage on providing the jQuery-based functionality required to operate the controls on the video; this is the functionality that would otherwise be provided by the browser's default video controls, which we will be hiding in the next task.

There's more...

You will notice that I've used the Google CDN links for jQuery and jQuery UI—while this is perfectly acceptable (and in some cases preferable), you may prefer to use a custom download at least for jQuery UI, which can reduce the size of the file to a more manageable 20KB. If you want to use this alternative, you will need to build a custom download, at http://www.jqueryui.com/download, to include the Core, Widget, Mouse, and Slider elements. The code will need to be altered as well—change the Google CDN link for this (assuming you are following the structure outlined at the start of the task):

<script type="text/javascript" src="js/jquery.ui.min.js">
</script>