Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > HTML/XHTML

Introducing HTML5: Video and Audio

  • Print
  • + Share This
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, but most of the markup and scripting are applicable for both audio and video.
This chapter is from the book

This chapter is from the book

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="https://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.

Normally, this is not a problem, but issues can arise when your layout overlaps the plugin’s drawing area. Imagine, for example, a site that contains a movie but also has JavaScript or CSS-based drop-down menus that need to unfold over the movie. By default, the plugin’s drawing area sits on top of the web page, meaning that these menus will strangely appear behind the movie.

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.

So now, <video> elements can be styled with CSS. They can be resized on hover using CSS transitions, for example. They can be tweaked and redisplayed onto <canvas> with JavaScript. Best of all, the innate hackability that open web standards provide is opened up. Previously, all your video data was locked away; your bits were trapped in a box. With HTML5 multimedia, your bits are free to be manipulated however you want.

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:

<video src=turkish.webm></video>

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

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.

autoplay

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>

controls

Providing controls is approximately 764 percent better than autoplaying your video. See Figure 4.2. You can use some simple JavaScript to write your own (more on that later) or you can tell the browser to provide them automatically:

<video src=leverage-a-synergy.webm controls>
</video>
Figure 4.2

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 the <audio> element has the controls attribute, you’ll see them on the page. Without the attribute, you can hear the audio but nothing is rendered visually on the page at all; it is, of course, there in the DOM and fully controllable via JavaScript and the new APIs.

poster

The poster attribute points to an image that the browser will use while the video is downloading, or until the user tells the video to play. (This attribute is not applicable to <audio>.) It removes the need for additional tricks like displaying an image and then removing it via JavaScript when the video is started.

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.

muted

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>

height, width

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.

loop

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.

preload

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.

  • preload=none

    This state suggests to the browser that it shouldn’t preload the resource until the user activates the controls.

  • preload=metadata

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.

src

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.

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020