Lesson 9: Working with Video and Audio Elements

html5_04_opener.psd

Adding video and sound to a web page makes a 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 deliver 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_09lessons folder in this lesson. Make sure you have loaded the HTML5lessons folder onto your hard drive from www.digitalclassroombooks.com/HTML5. See “Loading lesson files” in the Starting Up section of this book.

To accurately preview the HTML5 content you will create in this lesson, you need a browser that supports HTML5 tags. See “Using web browsers that support HTML5 tags” 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_09lessons 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 begin playing automatically.

3770.jpg

The video element displayed in Firefox.

4985.jpg If you do not see video playing, it is possible you need to update your browser. For 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, 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:

<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.

3754.jpg

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:

<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.

3738.jpg

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 attributes:

<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:

poster='poster320.jpg'

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

3721.jpg

The video element resized to 320 × 180.

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 open standard, open source–friendly, and is 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:

<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:

<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 is 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.

4993.jpg For more information on supported media types and current browser support for each type, visit: http://wiki.whatwg.org/wiki/Video_type_parameters.

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:

<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 message to download the video.

3705.jpg

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.

4998.jpg 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.

<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. 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.

3688.jpg

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

5004.jpg 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:

<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.

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 exercise, you will learn to add a button that stretches to the natural width of the video and controls whether the video is playing or paused.

1 From the HTML5_09lessons 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.

5010.jpg In this exercise, you should use either the latest version of Google Chrome or Mozilla Firefox. Other browsers (or older versions of Chrome/Firefox) may not display the video or the Play button may not appear as indicated.

3673.jpg

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:

<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.

3654.jpg

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 onloadedmetadata event of the video element and set the value to setButtonWidth() as follows:

<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:

3638.jpg

The width of the input button dynamically set to the 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:

<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:

<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:

<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 website.

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_09lessons 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:

3620.jpg

An audio element using the native browser controls.

Recall that there is no visual component to the media file; 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.

<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

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 play if the user’s browser does not support H.264, are needed.

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

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