Introducing HTML5: Video and Audio
A LONG TIME AGO, in a galaxy that feels a very long way away, multimedia on the Web was limited to tinkling MIDI tunes and animated GIFs. As bandwidth got faster and compression technologies improved, MP3 music supplanted MIDI and real video began to gain ground. All sorts of proprietary players battled it out—Real Player, Windows Media, and so on—until one emerged as the victor in 2005: Adobe Flash, largely because of its ubiquitous plugin and the fact that it was the delivery mechanism of choice for YouTube.
HTML5 provides a competing, open standard for delivery of multimedia on the Web with its native video and audio elements and APIs. This chapter largely discusses the <video> element, as that’s sexier, but most of the markup and scripting are applicable to <audio> as well.
Native multimedia: why, what, and how?
In 2007, Anne van Kesteren wrote to the Working Group:
“Opera has some internal experimental builds with an implementation of a <video> element. The element exposes a simple API (for the moment) much like the Audio() object: play(), pause(), stop(). The idea is that it works like <object> except that it has special <video> semantics much like <img> has image semantics.”
While the API has increased in complexity, van Kesteren’s original announcement is now implemented in all the major browsers, including Internet Explorer 9.
An obvious companion to a <video> element is an <audio> element; they share many similar features, so in this chapter we discuss them together and note only the differences.
<video>: Why do you need a <video> element?
Previously, if developers wanted to include video in a web page, they had to make use of the <object> element, which is a generic container for “foreign objects.” Due to browser inconsistencies, they would also need to use the previously invalid <embed> element and duplicate many parameters. This resulted in code that looked much like this:
<object width="425" height="344"> <param name="movie" value="http://www.youtube.com/v/9sEI1AUFJKw&hl=en_GB&fs=1&"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/9sEI1AUFJKw&hl=en_GB&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed> </object>
This code is ugly and ungainly. Worse still is the fact that the browser has to pass the video off to a third-party plugin; hope that the user has the correct version of that plugin (or has the rights to download and install it, and the knowledge of how to do so); and then hope that the plugin is keyboard accessible—along with all the other unknowns involved in handing the content to a third-party application.
Plugins can also be a significant cause of browser instability and can create worry for less technical users when they are prompted to download and install newer versions.
Whenever you include a plugin in your pages, you’re reserving a certain drawing area that the browser delegates to the plugin. As far as the browser is concerned, the plugin’s area remains a black box—the browser does not process or interpret anything that happens there.
Problems and quirks can also arise if your page has dynamic layout changes. Resizing the dimensions of the plugin’s drawing area can sometimes have unforeseen effects—a movie playing in the plugin may not resize, but instead simply may be cropped or display extra white space. HTML5 provides a standardised way to play video directly in the browser, with no plugins required.
One of the major advantages of the HTML5 video element is that, finally, video is a full-fledged citizen on the Web. It’s no longer shunted off to the hinterland of <object> or the nonvalidating <embed> element.
What HTML5 multimedia isn’t good for
Regardless of the sensationalist headlines of the tech journalists, HTML5 won’t “kill” all plugins overnight. There are use-cases for plugins not covered by the new spec.
Copy protection is one area not dealt with by HTML5—unsurprisingly, given that it’s a standard based on openness. So people who need digital rights management (DRM) are probably not going to want to use HTML5 video or audio, as they’ll be as easy to download to a hard drive as an <img> is now. Some browsers offer simple context-menu access to the URL of the video, or even let the user save the video. Developers can view source, find the reference to the video’s URL, and download it that way. (Of course, you don’t need us to point out that DRM is a fool’s errand, anyway. All you do is alienate your honest users while causing minor inconvenience to dedicated pirates.)
HTML5 can’t give us adaptive streaming either. This is a process that adjusts the quality of a video delivered to a browser based on changes to network conditions to ensure the best experience. It’s being worked on, but it isn’t there yet.
Plugins currently remain the best cross-browser option for accessing the user’s webcam or microphone and then transmitting video and audio from the user’s machine to a web page such as Daily Mugshot or Chatroulette, although getUserMedia and WebRTC are in the cards for Chrome, Opera, and Firefox—see “Video conferencing, augmented reality” at the end of this chapter. After shuddering at the unimaginable loneliness that a world without Chatroulette would represent, consider also the massive amount of content already out there on the web that will require plugins to render it for a long time to come.
Anatomy of the video and audio elements
At its simplest, to include video on a page in HTML5 merely requires this code:
The .webm file extension is used here to point to a WebM-encoded video.
Similar to <object>, you can put fallback markup between the tags for older web browsers that do not support native video. You should at least supply a link to the video so users can download it to their hard drives and watch it later on the operating system’s media player. Figure 4.1 shows this code in a modern browser and fallback content in a legacy browser.
<h1>Video and legacy browser fallback</h1> <video src=leverage-a-synergy.webm> Download the <a href=leverage-a-synergy.webm>How to leverage a synergy video</a> </video>
Figure 4.1 HTML5 video in a modern browser and fallback content in a legacy browser.
However, this example won’t actually do anything just yet. All you can see here is the first frame of the movie. That’s because you haven’t told the video to play, and you haven’t told the browser to provide any controls for playing or pausing the video.
While you can tell the browser to play the video or audio automatically once the web page is loaded, you almost certainly shouldn’t, as many users (and particularly those using assistive technology, such as a screen reader) will find it highly intrusive. Users on mobile devices probably won’t want you using their bandwidth without them explicitly asking for the video. Nevertheless, here’s how you do it:
<video src=leverage-a-synergy.webm autoplay> <!-- your fallback content here --> </video>
<video src=leverage-a-synergy.webm controls> </video>
Figure 4.2 The default controls in Firefox. (These are similar in all modern browsers.)
Naturally, these differ between browsers, as the spec doesn’t prescribe what the controls should look like or do, but most browsers don’t reinvent the wheel and instead have stuck to what has become the general norm for such controls—there’s a play/pause toggle, a seek bar, and volume control.
Browsers have chosen to visually hide the controls, and only make them appear when the user hovers or sets focus on the controls via the keyboard. It’s also possible to move through the different controls using only the keyboard. This native keyboard accessibility is already an improvement on plugins, which can be tricky to tab into from surrounding HTML content.
If you don’t use the poster attribute, the browser shows the first frame of the movie, which may not be the representative image you want to show.
The behavior varies somewhat on mobile devices. Mobile Safari does grab the first frame if no poster is specified; Opera Mobile conserves bandwidth and leaves a blank container.
The muted attribute, a recent addition to the spec (read: “as yet, very little support”), gives a way to have the multimedia element muted by default, requiring user action to unmute it. This video (an advertisement) autoplays, but to avoid annoying users, it does so without sound, and allows the user to turn the sound on:
<video src="adverts.cgi?kind=video" controls autoplay loop muted></video>
The height and width attributes tell the browser the size of the video in pixels. (They are not applicable to <audio>.) If you leave them out, the browser uses the intrinsic width of the video resource, if that is available. Otherwise it uses the intrinsic width of the poster frame, if that is available. If neither is available, the browser defaults to 300 pixels.
If you specify one value but not the other, the browser adjusts the size of the unspecified dimension to preserve the video’s aspect ratio.
If you set both width and height to an aspect ratio that doesn’t match that of the video, the video is not stretched to those dimensions but is rendered letterboxed inside the video element of your specified size while retaining the aspect ratio.
The loop attribute is another Boolean attribute. As you would imagine, it loops the media playback. Support is flaky at the moment, so don’t expect to be able to have a short audio sample and be able to loop it seamlessly. Support will get better—browsers as media players is a new phenomenon.
Maybe you’re pretty sure that the user wants to activate the media (she’s drilled down to it from some navigation, for example, or it’s the only reason to be on the page), but you don’t want to use autoplay. If so, you can suggest that the browser preload the video so that it begins buffering when the page loads in the expectation that the user will activate the controls.
<video src=leverage-a-synergy.ogv controls preload> </video>
There are three spec-defined values for the preload attribute. If you just say preload, the user agent can decide what to do. A mobile browser may, for example, default to not preloading until explicitly told to do so by the user. It’s important to remember that a web developer can’t control the browser’s behavior: preload is a hint, not a command. The browser will make its decision based on the device it’s on, current network conditions, and other factors.
preload=auto (or just preload)
This is a suggestion to the browser that it should begin downloading the entire file.
This state suggests to the browser that it shouldn’t preload the resource until the user activates the controls.
This state suggests to the browser that it should just prefetch metadata (dimensions, first frame, track list, duration, and so on) but that it shouldn’t download anything further until the user activates the controls.
As on an <img>, the src attribute points to audio or video resource, which the browser will play if it supports the specific codec/container format. Using a single source file with the src attribute is really only useful for rapid prototyping or for intranet sites where you know the user’s browser and which codecs it supports.
However, because not all browsers can play the same formats, in production environments you need to have more than one source file. We’ll cover this in the next section.