Creative Digital Media

History is recorded moments in life. People’s thoughts, either great among others or just great in their own shadow. Every glimpse of life at that just moment, deserves to be treasured. So just “Keep That Thought”…

Building a Mobile Responsive HTML5 Video Player

The new HTML5 media trends are very popular chatter among web developers. It’s now easier than ever before to embed custom video or audio into your website. And best of all, modern web browsers are starting to adapt these trends so that we’re constantly pushing towards a single set of accepted file formats.

But in this tutorial I would like to share some ideas related to embedding custom HTML5 video. I want to use the open source HTML5 Media project as an example of one library we can include for interactive web development. I will also explain how we can make the video layout responsive so all the content will be fluid on mobile phones.

I’m hoping this tutorial will provide an introduction into embedded video media. In the past most web developers have been working with a custom flash player, which has been acceptable until recently. Now that the iPhone has absolutely no support for Flash plugins we need to push for an alternative. And the most promising advancement towards the future looks to be HTML5.

Building a Mobile Responsive HTML5 Video Player

Hit the screenshot to see the preview, press Space to play, to see how video adapts to different resolutions simply scale the page. Hit the link to download the Source Code.

Specific Media File Types

Before we jump into the code I’d like to explain the separation of file types. Apple devices have always been supporting .mp4 video which is undoubtedly the most common. Practically everything can support .mp4 video except Firefox and older versions of Internet Explorer.

The alternative to these video formats is WebM which has been growing very quickly. These videos are generally high quality with lower file sizes, which makes them very quick to stream over the Internet. Between just these two filetypes you can support 99% of the visitors who come onto your page.

If somebody is using an older browser which doesn’t support either webm or mp4 then you could always try serving up a Flash alternative. Every browser including IE6 has support for Adobe Flash if the proper plugins are installed. MP4 videos use the H.264 codec which can be passed into any Flash video player and streams perfectly.

Many developers still try to support the OGG filetype which was really a spinoff from older versions of Firefox. All these releases are currently outdated, and so I don’t find OGG to be particularly interesting. Firefox 3.6 is the only version which doesn’t support WebM yet supports OGG. And obviously as more people update their Firefox installation these problems will naturally fix themselves. If you’re interested in these trends check out this great HTML5 video webpage which has some charts and statistical data for web developers.

Setting the Document Header

To get started let’s create a new blank index.html file. I’ll be adding in my own custom header information right after the HTML5 doctype declaration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>HTML5 Responsive Video Player</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="HandheldFriendly" content="true">
  <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
  <script type="text/javascript" <src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://api.html5media.info/1.1.5/html5media.min.js"></script>
  <!--[if lt IE 9]>
  <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
</head>

It’s understandable how we need to include a large amount of custom tags in the document header section. The meta tags such as X-UA-Compatible and viewport are needed to force all mobile browsers into a 100% zoom state. That way the users aren’t pinching to zoom into the page every time it’s loaded onto an iPhone or iPad.

I’ve included a script resource to the most recent release of jQuery 1.7.2 hosted by Google. We are also using the HTML5Media script hosted directly on their website. The current release is at 1.1.5 but I would be expecting updates in the near future. Of course if you would rather store a local copy of the script that’s fine too. But when you’re creating a small web application it’s nice to have the option of linking to their server instead.

The last bit of interesting code is only included for Internet Explorer versions 8 or lower. These versions do not natively support HTML5 elements and so we need to setup the default tag names and CSS styles to be recognized in legacy browsers. This can be accomplished with the HTML5shiv project also hosted on Google’s CDN.

Embedding Video

With the header pieced together nicely we can start looking into HTML5 embed codes. Using these media libraries we just need to point towards our specific source files and the rendering engines will do the rest.

In this example I’ll be using the two default file types I mentioned earlier. MP4 is offered first because this is a requirement for supporting older iOS software on iPads and iPhones. I’m also setting the max width & height for the video file, along with a poster image which is displayed right when the page first loads.

1
2
3
4
5
6
7
8
9
<div id="wrapper">
  <h1>Mobile Responsive Video Player</h1>
  <p class="note">Press the space button for Play/Pause</p>

  <video poster="images/winsome-preview.png" width="640" height="480" controls preload>
    <source src="media/104.winsome.witch.mp4" type="video/mp4"></source>
    <source src="media/104.winsome.witch.webm" type="video/webm"></source>
  </video>
</div>

Now to make this element responsive we need to setup a CSS max-width property. This is a nice CSS trick which is commonly used on images to be responsive following the browser width. This allows the media content to resize smaller if there is less screen real estate, but it will never be larger than the full maximum width.

1
video { max-width: 100%; height: auto; }

Some Added JavaScript Tricks

When finishing this tutorial I also wanted to include a small block of jQuery into the main HTML file. The first block deals with playing the video whenever you click anywhere in the media box.

By default Firefox already supports this feature in HTML5 video formats. When you click anywhere on the media box the video will play/pause automatically. However this is not the case with Internet Explorer, Safari, Chrome, or Opera. So first we check if the browser is Mozilla-based using a conditional . If false then we add the functionality to play/pause the video when you click anywhere in the media element.

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready(function(){
  $("video").on("click", function(){
    if(!$.browser.mozilla) {
    // mozilla HTML5 video auto-supports auto click-to-play
    // otherwise we add this functionality ourselves
      if(this.paused == true) {
        this.play();
      } else {
        this.pause();
      }
    } // end mozilla browser check
  }); // end video click handler

Now the 2nd bit of functionality is adding support for hitting the spacebar which should trigger play/pause. By default this can work in some browsers, but only if you are focused on the video element. That doesn’t exactly help a whole lot so I’ve added a key event onto the HTML document itself.

We check whenever the user hits a key and pass the event into a new function. Then we can match the key ID against the spacebar ID(#32). If there’s a match then we first use e.preventDefault(); to stop the space bar from scrolling down the page. Then we target the first video element on the page and perform the same play/pause logic seen earlier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  $("html, video").on("keydown", function(e){
    var kcode = (e.keyCode ? e.keyCode : e.which);
    var viddy = $("video")[0];

    if(kcode == 32) {
      // if space bar stop default scrolling and start/stop video player
      e.preventDefault();

      if(viddy.paused == true) {
        viddy.play();
      } else {
        viddy.pause();
      }
    } // end if keycode logic
  }); // end keydown event handler
});

And that should cover all the important pieces! This is a great video template for just getting started working with HTML5 embed codes. It goes to show how quickly you can get up & running with 3rd party open source solutions such as HTML5 Media. Plus the small bit of added jQuery functionality really adds a stock solution for cross-browser support.

Building a Mobile Responsive HTML5 Video Player

Hit the screenshot to see the preview, press Space to play, to see how video adapts to different resolutions simply scale the page. Hit the link to download the Source Code.

Final Thoughts

I sincerely hope that you can take some ideas away from this tutorial and implement them into your own website. It takes a lot of practice building a successful web application. You won’t get everything right on the first try, but keep pushing forward and don’t be afraid of trying new things.

If you’d like to check out my demo you can do so above and also download the original source code files. I like to offer tutorials as open source so that other developers can learn from these techniques. Feel free to play around with the code and even extend my functionality. Also if you have any suggestions or ideas about the tutorial feel free to share with us in the post comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on August 27, 2012 by in Web Design, Webtools and tagged , .