HTML5 Digital Classroom Book

HTML5 book
HTML5 Digital Classroom is like having a personal instructor guiding you through each lesson, while you work at your own pace. This HTML5 book includes 15 self-paced lessons that allow you to learn the new features enabled in HTML5 and how to code modern web pages at your own speed.
  • Full color lessons with easy to follow step-by-step instructions | view sample lesson
  • Video tutorials highlight key topics in each lesson | sample HTML5 video tutorial
  • Covers all essential HTML5 skills | view Table of Contents
  • Gets you up-and-running quickly with included lesson files
  • Written by expert HTML5 instructors who regularly teach HTML5 training courses – it's like having your own personal tutor
  • Used by hundreds of schools and more than 100,000 readers

Are you an Instructor or Professor?

Contact your Wiley higher education representative to obtain a review copy or use the contact form to obtain an instructor's guide for using the Digital Classroom as your HTML5 class textbook.

Lesson 4 Working with Video and Audio Elements

Adding video and sound to a web page is one way to make your website more engaging. Media provides a way to grab the attention of your visitors, and it also provides a way to reach audiences that would otherwise bypass long lengths of text. HTML5 directly addresses the need to play both video and audio.

What you'll learn in this lesson:
  • Adding video with the <video> element
  • Adding audio with the <audio> element
  • Providing fallbacks for browsers
  • Controlling a video with JavaScript

Starting up

You will work with several files from the HTML5_04lessons folder in this lesson. Make sure you have copied the HTML5lessons folder onto your hard drive. See “Loading lesson files” in the Starting Up section of this book.

  • video
    See Lesson 4 in Action! Use the accompanying video to gain a better understanding of how to use some of the features shown in this lesson. The video tutorial for this lesson can be found on the included DVD.

To accurately preview the HTML5 content you will create in this lesson, you need a browser that supports HTML5 tags. See “Use a browser that supports HTML5” in the Starting Up section of this book to determine whether you are using such a browser, or for instructions on downloading one.

Adding video

Before the advent of HTML5, you needed third party plug-ins such as Flash, QuickTime, or Silverlight to show video. HTML5 has replaced this need by specifying an HTML video element that runs natively in the browser and integrates with JavaScript.

In this section, you will learn to add video to your Web page such that the video begins automatically when the page loads, and takes advantage of the native browser player controls.

1 From the HTML5_04lessons folder, open the index.html page. On line 8 inside the body element, add the following line of code.

<video src='videos/BigBuck.ogg' autoplay></video>

As is the case with the image element, the video element has an src attribute where the value points to the location of the video file you want to play. The autoplay attribute tells the browser to begin playing the video as soon as the page loads.

Save the file and preview the Web page in the latest versions of Chrome, Firefox, or Opera. You should see a page similar to the figure below; the video should being playing automatically.

html5_04_01.ai

The video element displayed in Firefox.

  • Note
    If you do not see video playing it is possible you need to update your browser. Fore more information on the importance of this be sure to read the “Starting Up” section of the book

Since there is a standard way to declare a video in HTML, the browser developers have the responsibility of ensuring the browser follows the standard and displays the video properly. As a Web developer, your job is to focus on your content and customizations.

2 To provide more control over the video playback, remove the autoplay attribute and add a controls attribute so your line of code appears as follows (highlighted in red):

<video src='videos/BigBuck.ogg' controls ></video>

Save your work, then move to your Web browser. If the page is open, refresh the page in your Web browser; if the page is closed, re-open the work file you are using for this lesson. The figures below show the native browser controls for Chrome, Firefox, and Opera.

html5_04_02.ai

Native browser controls in Chrome, Firefox, and Opera.

Click the play button and the video should begin. Drag the slider bar and the current position of the video should change accordingly.

Just by adding the controls attribute to the video element, each browser adds interactive playback controls including a play/pause button, time codes, volume control, and position slider.

With the autoplay attribute removed, the first frame or black rectangle appears on the screen until the video begins playing. If you want to display a custom preview image instead of the first frame or black rectangle, use the poster attribute.

3 Add the poster attribute after the controls attribute and set the value to "poster854.jpg" as follows (highlighted in red):

<video src='videos/BigBuck.ogg' controls poster='poster854.jpg'></video>

Setting the poster attribute tells the browser to load an image and place it above the video element. Once the video begins, the image disappears and the video is displayed.

Save your file and refresh your browser. You will see the poster image now instead of a black screen.

html5_04_03.ai

A preview image is now shown when the page loads.

By default, the video element is resized to fit the encoded media file. To control the size of the video element, use the width and height attributes.

4 Add the following width and height attribute and values (highlighted in red):

<video src=’videos/BigBuck.ogg’ controls poster=’poster854.jpg’ width=’320’ height=’180’></video>

This resizes the video but you should also substitute a small poster image as well. Change the value of the poster as follows (highlighted in red):

poster=’poster320.jpg’

5 Save the file and refresh your browser; the Web page should appear similar to the following figure.

html5_04_04.ai

The video element resized to 320 × 180.

Additional attibutes

In additon to the autoplay, controls and poster attributes, the video element has a few other attributes for use:

audio: This attribute allows you to mute the volume of your video. Currently, the only supported value is ‘muted’.

loop: This attribute will trigger your video to automatically begin playing again when it reaches the end.

preload: This attribute will allow you to begin loading the video as soon as the page loads and can reduce the amount of time it takes to load when the user clicks play.

Adding support for more browsers

There are many formats and codec for video, and not all are supported equally across the different HTML5-enabled Web browsers. Each video file acts as a container for multiple files that contain the audio and video. The Ogg format is an open standard, open source–friendly, and supported natively by the latest versions of Chrome, Firefox, and Opera.

Another popular Web video format is MP4, specifically, an MP4-containing video that uses the H.264 codec and audio that uses the AAC codec. Both H.264 and AAC codecs also support multiple levels of profiles, which are used to provide different levels of compression and quality. To reach the widest array of devices and browsers, you should use the baseline profile for H.264 video and the “low complexity” profile AAC.

MP4 files encoded as explained in the previous paragraph are supported by the latest versions of Internet Explorer, Safari, iOS, and Android. Making your videos available in both Ogg and MP4 formats lets you to reach the most users with modern browsers and devices. In this section, you will learn to add multiple source files to a video element, which allows the browser to select the file based on the format it supports.

1 Remove the src attribute from the video element.

2 Add a source element as a child of the video element and set the src attribute of the source element to 'videos/BigBuck.ogg' as follows (highlighted in red).

<video controls poster='poster320.jpg' width='320' height='180'>

<source src='videos/BigBuck.ogg' />

</video>

3 Add another child source element below the one from the previous step and set the src attribute to videos/BigBuck.mp4. as follows (highlighted in red):

<video controls poster=’poster320.jpg’ width=’320’ height=’180’>

<source src=’videos/BigBuck.ogg’ />

<source src=’videos/BigBuck.mp4’ />

</video>

4 Save your file and refresh the Web page in a browser. When you open your HTML code in Chrome, Firefox, or Opera, the first source file is used because the browsers support the Ogg file format. When you open your HTML code in Internet Explorer or Safari, the second source file is used because the MP4 format is supported.

The Web browser checks source files for compatibility in the order they appear in the video element. In this scenario, Internet Explorer and Safari download enough of the Ogg formatted file to attempt to load the file. When the file cannot be loaded, the browser moves from the current source file to the next source file. The browser continues to attempt to load each source file until a compatible file is found or there are no more files to try.

To assist the browsers in determining compatible files and prevent the user from downloading unsupported files, you can use the type attribute of the source element. The value of the type attribute describes the file format, video codec, and audio codec of the source file.

5 Add a type attribute to the first source element to describe the Ogg file format using the following syntax.

<source src='videos/BigBuck.ogg' type='video/ogg; codecs="theora, vorbis"'>

This tells the browser that the “BigBuck.ogg” file is saved in the Ogg file format, and that the video was with the Theora codec, and that the audio is encoded with the Vorbis codec.

For the MP4 file, add the following value for the type attribute to the second source element.

<source src='videos/BigBuck.mp4' type='video/mp4; codecs="avc1.42E01E,
mp4a.40.2"'
>

This tells the browser that the “BigBuck.mp4” file is saved in the MP4 format, the video encoded with H.264 using the baseline profile, and the audio is encoded with the AAC codec using the “low complexity” profile.

When the browser loads your HTML code, it checks for compatibility based on the type attribute and saves time and bandwidth by not downloading every file.

Once you set up support for a variety of modern browsers, you can add additional code for older browsers that do not support HTML5: when your page is loaded in an older browser that does not support the video element, it will ignore it and use the alternative.

Adding fallback support for older browsers

1 Add an h1 element with a link to the “BigBuck.mp4” file after the second source element as follows (highlighted in red).

<video controls poster='poster320.jpg' width='320' height='180'>

<source src='videos/BigBuck.ogg' type='video/ogg; codecs="theora, vorbis"'>

<source src='videos/BigBuck.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>

<h1><a href="videos/BigBuck.mp4">Download the video</a></h1>

</video>

If you save the file and load the Web page in an older browser that does not support HTML5, you would see the following message.

html5_04_05.ai

The fallback message displayed in a browser with no HTML5 support.

If you load the same HTML code in a modern browser, the h1 element and the download link will be ignored because the video element is supported.

To provide an even better alternative for older browsers, you can use Flash as a backup to play the video on the Web page. Using the same technique as the last step to provide alternate HTML for unsupported elements, you can use an object element that references a Flash file as the last child of the source elements.

  • Note
    FlowPlayer is an open source Flash-based video player released under a GPL license. A Flash-based fallback video player is useful because Flash supports the MP4 video format and is installed on the majority of computers connected to the Internet. The FlowPlayer files are included within the lesson folder in the player folder. For more information on FlowPlayer, visit their site at flowplayer.org.

2 Remove the fallback h1 element from the previous step and insert an object element with the following properties and child elements (highlighted in red).

<video controls poster='poster320.jpg' width='320' height='180'>

<source src='videos/BigBuck.ogg' type='video/ogg; codecs="theora, vorbis"'>

<source src='videos/BigBuck.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>

<object width="320" height="180" type="application/x-shockwave-flash" data="player/flowplayer-3.2.5.swf">

<param name="movie" value="player/flowplayer-3.2.5.swf" />

<param name="allowfullscreen" value="true" />

<param name="flashvars" value='config={"clip": {"url": "videos/BigBuck.mp4", "autoPlay":false, "autoBuffering":true}}' />

</object>

</video>

A complete description of this code is beyond the scope of this lesson; however, the following is an overview of what the code means.

The object element tells the browser to load the Flash player plug-in and run the “flowplayer-3.2.5.swf” file of the same size as the video element. The path to the MP4 file is then passed using the flashvars parameter.

3 If you save this file and load the page in an older browser that does not support HTML5, the browser bypasses the source and video elements and loads the object element. If the Flash player is installed, the page should appear similar to the following figure.

html5_04_06.ai

A Flash player loaded as a fallback for browsers with no HTML5 support.

  • Note
    To ensure the best performance you should make sure the latest version of the Flash Player is installed on your system. In older versions of the Flash Player you may see video but no fullscreen option. Visit http://get.adobe.com/flashplayer/ to install the latest version

4 As a final fallback measure, add the h1 element from the previous step as a child element of the object element after the third param element (highlighted in red).

<object width="320" height="180" type="application/x-shockwave-flash" data="player/flowplayer-3.2.5.swf">

<param name="movie" value="player/flowplayer-3.2.5.swf" />

<param name="allowfullscreen" value="true" />

<param name="flashvars" value='config={"clip": {"url": "videos/BigBuck.mp4", "autoPlay":false, "autoBuffering":true}}' />

<h1><a href="videos/BigBuck.mp4">Download the video</a></h1>

</object>

To review, the following scenarios are now supported:

  • If the browser supports the video element, the source elements are analyzed and a supported format is selected.
  • If the video element is not supported and the Flash player plug-in is installed, the MP4 file is used in the flash-based video player.
  • If the video element is not supported and the Flash player plug-in is not installed, the h1 element is displayed and the MP4 file is made available for download.

The WebM video format

In the Spring of 2010, Google announced the WebM video codec, an alternative to OGG and H.264. In the winter of 2011, it was announced that Google’s Chrome browser would only support OGG video and the WebM format but not H.264.

Although the adoption of WebM video is currently small, there is no doubt it will grow in the near future. Mozilla Firefox recently added support for WebM in Firefox 4 and Microsoft has also released a component plugin that allows WebM to run in Internet Explorer 9 (and presumably 10).

Of course this leaves out Apple’s Safari, both for desktop and mobile. Apple has not announced any support for the WebM format at this time, preferring to focus on H.264. The addition of the WebM format can add to the confusing landscape for those not familiar with web video. The key point is to remember that there is no single video format that will work across all browsers and devices and it will be necessary to provide fallbacks to users for quite some time.

Controlling a video with JavaScript

In some scenarios, such as adding custom graphics or integrating media playback with other elements of the page, you might not want to use the native browser controls for the video element. To facilitate these types of situations, the video element exposes a JavaScript-based API to control media playback and retrieve properties of the video.

In this lesson, you will learn to add a button that stretches to the natural width of the video and controls whether video is playing or paused.

1 From the HTML5_04lessons folder, open the controlling.html page. You will find a simple video tag that uses the Ogg file from the previous lesson as its source.

html5_04_07.ai

The video element loaded on the page.

Note that the element resizes to the natural width and height of the encoded video because there is no explicit width or height set on the video element.

2 Add a break element after the video element to position the upcoming button below the video element. After the break element, add an input element with the type attribute set to "button" and the value attribute set to "Play". Additionally, add an id attribute with a value of "playPause" as follows (highlighted in red).

<video src="videos/BigBuck.ogg"></video>

<br />

<input type="button" value="Play" id="playPause" />

Save your file and preview the Web page in Chrome; the page should appear similar to the following figure.

html5_04_08.ai

The video element and the input button.

3 To change the width of the button to match the width of the video, you must capture the video width once the metadata of the file has loaded, and then set the button width accordingly.

To capture the width of the video, add an event handler to the loadedmetadata event of the video element and set the value to "setButtonWidth()" as follows (highlighted in red):

<video src="videos/BigBuck.ogg" onloadedmetadata="setButtonWidth()"></video>

Next, you need to define variables in JavaScript that reference the video element and the input element.

4 Between the open and close script elements add the following lines:

var video = document.getElementsByTagName('video')[0];

var playPause = document.getElementById('playPause');

The first line reads a reference to the first video element on the page and saves it in a variable called video. The next line finds the input element by ID and saves a reference to it in a variable called playPause. On the next line add the setButtonWidth function as follows:

function setButtonWidth(e){

playPause.style.width = video.videoWidth + 'px';

}

Save your file and preview the Web page in Chrome; the page should appear as follows:

html5_04_09.ai

The width of the input button dynamically set to same width of the video.

To control the playback of the video with the click of the button, however, you must add event handlers for the play and pause events. You can use the same function to handle both events by first checking the paused property of the video element.

5 Add event handlers to the video element for play and pause and set the value to "setPlayPause()" as follows (highlighted in red):

<video src="videos/BigBuck.ogg" onloadedmetadata="setButtonWidth()" onplay="setPlayPause()" onpause="setPlayPause()"></video>

6 Next, add an event handler to the click event of the button that instructs the video to play. You can define this code inline as follows (highlighted in red).

<input type="button" value="Play" id="playPause"
onclick="video.play()" />

7 The last step is to define the setPlayPause function that toggles the button click event and text values between play and pause. Add this code within your <script> element as follows (highlighted in red):

<script type=”text/javascript”>

var video = document.getElementsByTagName(‘video’)[0];

var playPause = document.getElementById(‘playPause’);

function setButtonWidth(e){

playPause.style.width = video.videoWidth + ‘px’;

}

function setPlayPause(e){

if(video.paused) {

playPause.value = 'Play';

playPause.onclick = function(e) { video.play(); }

} else {

playPause.value = 'Pause';

playPause.onclick = function(e) { video.pause(); }

}

}

Save your file and preview the Web page in Chrome. When the button is pressed, the text should change to “Pause” and the video should begin playing. Pressing the button a second time should pause the video and the text should change to “Play”.

There are many more properties and events exposed by the video element that allow you to completely recreate the native browser controls that can be found on the W3C Web site.

Adding audio

In some scenarios, such as podcasts and sound effects, you do not need to play both video and audio, and only need to play sound files. For such cases, the audio element comes in. The behavior, properties, and events of the audio element closely mirror the video element.

In this section, you will learn to add audio to your Web page that takes advantage of the native browser player controls.

1 From the HTML5_04lessons folder, open the audio.html page. On line 8 inside the body element, add the following line of code:

<audio src='videos/BigBuck.ogg' controls></audio>

Save the file and preview the Web page in Chrome, Firefox or Opera (you are using the Ogg format). Your browser’s native player will appear:

html5_04_10.ai

An audio element using the native browser controls.

Recall that there is no visual component to the media file; however, there are other supported file formats, such as MP3 and WAV. Additional media files without the video component hold less data and are much smaller in size.

2 Close your browser and return to your text editor. Remove the src attribute from the audio element and add a source element with src attribute set to "videos/BigBuck.ogg". And a second source element after the first with a source attribute set to "videos/BigBuck.mp3". (Changes highlighted in red.)

<audio controls>

<source src='videos/BigBuck.ogg' />

<source src='videos/BigBuck.mp3' />

</audio>

Save the file and preview your Web page in either Internet Explorer or Safari; the MP3 file should play when clicked.

Self study

1 The audio element is simple to use, practice repeating the “Controlling video with JavaScript” exercise using audio instead of video. When practicing the exercise be sure to replace the video element with the audio element in the source code.

Review

Questions

1 Name two attributes that you can add to the <video> element that can affect how video appears or works on your page.

2 What is a poster file and how would you use it?

3 Describe the role of a fallback as it relates to web video and name at least one example of one.

Answers

1 The controls attribute allows you to specify whether or not you want controls visible on your page. The autoplay attribute allows you to specify whether or not the video should be playing upon launch of the page. There are additional attributes as well such as width, height, loop, poster, preload and audio.

2 A poster file is an image file that you can specify as the introductory image for your video. Often the poster file will be a representative frame or image from your movie.

3 A fallback in web video is related to the need to provide more than one video source for users visiting your website. Because there is no single video format that is supported across all browsers/devices, fallbacks such as Flash video that plays if the user’s browser does not support H.264 are needed.

Congratulations! You have finished Lesson 4, “Working with Video and Audio Elements.”

split