HTML5 Video and Audio: The Markup

Share this article

HTML5 Video and Audio: The Markup

The following is an extract from our book, HTML5 & CSS3 for the Real World, 2nd Edition, written by Alexis Goldstein, Louis Lazaris, and Estelle Weyl. Copies are sold in stores worldwide, or you can buy it in ebook form here.

The Markup

After that necessary business surrounding containers, codecs, and licensing issues, it’s time to examine the markup of the video element and its associated attributes.

The simplest way to include HTML5 video in a web page is as follows:

<video src="example.webm"></video>

As you’ve probably figured out from the preceding sections, this will only work in a limited number of browsers. It is, however, the minimum code required to have HTML5 video working to some extent. In a perfect world, it would work everywhere—the same way the img element works everywhere—but that’s a little way off just yet.

Similar to the img element, the video element can also include width and height attributes:

<video src=”example.webm” width=”375″ height=”280″></video>

Even though the dimensions can be set in the markup, they’ll have no effect on the aspect ratio of the video. For example, if the video in the previous example was actually 375×240 and the markup was as shown, the video would be centered vertically inside the 280-pixel space specified in the HTML. This stops the video from stretching unnecessarily and looking distorted.

The width and height attributes accept integers only, and their values are always in pixels. Naturally, these values can be overridden via scripting or CSS.

Enabling Native Controls

No embedded video would be complete without giving the user the ability to play, pause, stop, seek through the video, or adjust the volume. HTML5’s video element includes a controls attribute that does just that:

<video src="example.webm" width="375" height="280" controls></video>

controls is a Boolean attribute, so no value is required. Its inclusion in the markup tells the browser to make the controls visible and accessible to the user.

Each browser is responsible for the look of the built-in video controls. Figure 5.1 and Figure 5.2 show how these controls differ in appearance from browser to browser.

Figure 5.1. The native video controls in Chrome
Figure 5.2. … in Firefox
Figure 5.3. … in Internet Explorer
Figure 5.4. … and in Opera

The autoplay Attribute

We’d love to omit reference to this particular attribute, since using it will be undesirable for the most part; however, there are cases where it can be appropriate. The Boolean autoplay attribute does exactly what its name implies: it tells the web page to play the video immediately as soon as possible.

Normally, this is a bad practice; most of us know too well how jarring it can be if a website starts playing video or audio as soon as it loads—especially if our speakers are turned up. Usability best practice dictates that sounds and movement on web pages should only be triggered when requested by the user. But this doesn’t mean that the autoplay attribute should never be used.

For example, if the page in question contains nothing but a video—that is, the user clicked on a link to a page for the sole purpose of viewing a specific video—it may be acceptable for it to play automatically, depending on the video’s size, surrounding content, viewing platform, and audience.

Here’s how you’d use this attribute:

<video src="example.webm" width="375" height="280" controls ↵autoplay></video>

Warning: Mobile Browsers Ignore autoplay

Many, if not all, mobile browsers will ignore the autoplay attribute, so the video will always wait for the user to press the play button before starting. This is sensible, given that mobile bandwidth is often limited and expensive.

The loop Attribute

Another available attribute that you should think twice before using is the Boolean loop attribute. Again, it’s fairly self-explanatory: according to the spec, this attribute will tell the browser to “seek back to the start of the media resource upon reaching the end.”

So if you created a web page whose sole intention was to annoy its visitors, it might contain code such as this:

<video src="example.webm" width="375" height="280" controls autoplay ↵loop></video>

Autoplay and an infinite loop! We’d just need to remove the native controls and we’d have a trifecta of worst practices.

Of course, as with autoplay, there are some situations where loop can be useful: a browser-based game in which ambient sounds and music should play continuously when the page is open, for example.

The preload Attribute

In contrast to the two previously discussed attributes, preload is certainly handy in a number of cases. The preload attribute accepts one of three values:

  • auto: indicates that the video and its associated metadata will start loading before the video is played. This way, the browser can start playing the video more quickly when the user requests it.
  • none: indicates that the video shouldn’t load in the background before the user presses play.
  • metadata: works like none, except that any metadata associated with the video (for example, its dimensions, duration, and the like) can be preloaded, even though the video itself won’t be.

The preload attribute has no spec-defined default in cases where it’s omitted; each browser decides which of those three values should be the default state. This makes sense, as it allows desktop browsers on good connections to preload the video and/or metadata automatically, having no real adverse effect; yet it permits mobile browsers to default to either metadata or none, as many mobile users have restricted bandwidth and will prefer to have the choice of whether or not to download the video.

The poster Attribute

When you attempt to view a video on the Web, usually a single frame of the video will be displayed in order to provide a teaser of its content. The poster attribute makes it easy to choose such a teaser. This attribute, similar to src, will point to an image file on the server by means of a URL.

Here’s how our video element would look with a poster attribute defined:

<video src="example.webm" width="375" height="280" controls ↵poster="teaser.jpg"></video>

If the poster attribute is omitted, the default “poster” will be the first frame of the video, which displays as soon as it’s loaded.

The muted Attribute

The muted attribute, a Boolean, controls the default state of the audio track for the video element.

Adding this attribute will cause the video’s audio track to default to muted, potentially overriding any user preferences. This will only control the default state of the element—a user interacting with the controls or JavaScript can change this.

Here it is added to our video element:

<video src="example.webm" width="375" height="280" poster= ↵"teaser.jpg" muted></video>

In previous versions of the HTML5 spec, there was an attribute called audio that took a value of muted. The new muted attribute replaces the audio attribute, which is now obsolete.

Adding Support for Multiple Video Formats

As we’ve discussed, there is currently no option to use a single container format to serve your video, even though that’s really the idea behind having the video element, and one which we hope will be realized in the near future. To include multiple video formats, the video element allows source elements to be defined so that you can allow each browser to display the video using the format of its choice. These elements serve the same function as the src attribute on the video element, so if you’re providing source elements, there’s no need to specify an src for your video element.

To achieve full browser support, here’s how we’ll declare our source elements:

<source src="example.mp4" type="video/mp4"> 
<source src="example.webm" type="video/webm"> 
<source src="example.ogv" type="video/ogg">

The source element (oddly enough) takes an src attribute that specifies the location of the video file. It also accepts a type attribute that specifies the container format for the resource being requested. This latter attribute enables the browser to determine if it can play the file in question, thus preventing it from unnecessarily downloading an unsupported format.

The type attribute allows also a codec parameter to be specified, which defines the video and audio codecs for the requested file. Here’s how our source elements will look with the codecs specified:

You’ll notice that the syntax for the type attribute has been slightly modified to accommodate the container and codec values. The double quotes surrounding the values have changed to single quotes, and another set of nested double quotes is included specifically for the codecs.

This can be a tad confusing at first glance, but in most cases you’ll just be copying and pasting those values once you have a set method for encoding the videos (which we’ll touch on later in this chapter). The important point is that you define the correct values for the specified file to ensure that the browser can determine which (if any) file it can play.

Note: Which formats do you need?

Depending on your website’s target audience, you may not require three source elements for full browser support. Support for video and audio codecs and containers is excellent, and you might only need one or two combinations. To help you decide which formats to use, be sure to check out the latest browser support info on Can I use.

Source Order

The three source elements are placed as children of the video element, and the browser being used to render the HTML will choose whichever container/codec format it recognizes—downloading only the resources it needs and ignoring the others. With our three file formats declared, our code will now look like this:

<video width="375" height="280" poster="teaser.jpg" audio="muted"> <source src="example.mp4" type='video/mp4; codecs="avc1.42E01E, ↵mp4a.40.2"'> <source src="example.webm" type='video/webm; codecs="vp8, ↵vorbis"'> <source src="example.ogv" type='video/ogg; codecs="theora, ↵vorbis"'> </video>

You’ll notice that our code is now without the src attribute on the video element. As mentioned, as well as being redundant, including it would override any video files defined in the source elements, so it’s necessary in this case to leave it out.

What about browsers without support for HTML5 video?

The three source elements that we included inside our video element will cover all modern browsers, but we’re yet to ensure that our video will play for older browsers. As has been mentioned, you might still have a significant percentage of users utilizing browsers without native support for HTML5 video. Most of those users are on some version of Internet Explorer prior to version 9.

In keeping with the principle of graceful degradation, the video element has been designed so that older browsers can access the video by some alternate means. Any browsers that fail to recognize the video element will simply ignore it, along with its source children. But if the video element contains content that the browser recognizes as valid HTML, it will read and display that content instead.

What kind of content can we serve to those non-supportingbrowsers? According to Adobe, over one billion desktop users have the Flash Player plugin installed on their systems. And most of those instances of the Flash plugin are version 9 or later, which offer support for the MPEG-4 video container format. With this in mind, to allow Internet Explorer 8 and earlier (and other older browsers without support for HTML5 video) to play our video, we can declare an embedded Flash video to use as a fallback. Here’s the completed code for the video on The HTML5 Herald with the Flash fallback code included:

<video width="375" height="280" poster="teaser.jpg" audio="muted">
  <source src="example.mp4" type='video/mp4; codecs="avc1.42E01E, 
  <source src="example.webm" type='video/webm; codecs="vp8, 
  <source src="example.ogv" type='video/ogg; codecs="theora, 
  <!-- fallback to Flash: -->
  <object width="375" height="280" type="application/x-shockwave-
↵flash" data="mediaplayer-5.5/player.swf">
    <param name="movie" value="mediaplayer-5.5/player.swf">
    <param name="allowFullScreen" value="true">
    <param name="wmode" value="transparent">
    <param name="flashvars" value="controlbar=over&amp;image=images/
    <!-- fallback image -->
    <img src="teaser.jpg" width="375" height="280" alt="" title="No 
↵video playback capabilities">

We’ll skip going into all the details of how this newly added code works (this isn’t a Flash book, after all!), but here are a few points to note about this addition to our markup:

  • The width and height attributes on the object element should be the same as those on the video element.
  • To play the file, we’re using the open-source JW Player by LongTail Video, which is free for non-commercial use, but you can use whichever video player you prefer.
  • The Flash video code has a fallback of its own—an image file that displays if the code for the Flash video fails to work.
  • The fourth param element defines the file to be used (example.mp4). As has been mentioned, most instances of the Flash player now support video playback using the MPEG-4 container format, so there’s no need to encode another video format.
  • HTML5-enabled browsers that support HTML5 video are instructed by the spec to ignore any content inside the video element that’s not a source tag, so the fallback is safe in all browsers.

In addition to the Flash fallback content, you could also provide an optional download video link that allows the user to access a local copy of the video and view it at their leisure. This would ensure that nobody is left without a means to view the video.

The last point to mention here is that, as is the case with the extra source elements, you may have no visitors from browsers without HTML5 video support on your website, or you might not be concerned about the small percentage using older browsers. In either of such cases, you could easily leave out the Flash fallback content and thus simplify the code.

Frequently Asked Questions (FAQs) about HTML5 Video and Audio Markup

What is the HTML5 video and audio markup?

HTML5 video and audio markup is a feature introduced in HTML5 that allows you to embed video and audio elements directly into your HTML code. This eliminates the need for external plugins or players, providing a seamless multimedia experience for users. The markup consists of the

Why am I getting a “HTML5 video file not found” error?

The “HTML5 video file not found” error typically occurs when the browser cannot locate or access the video file specified in the source attribute of the

How can I annotate my HTML5 video?

Annotating an HTML5 video involves adding text, shapes, or other elements over the video to provide additional information or highlight certain parts of the video. While HTML5 does not provide built-in annotation features, you can use JavaScript and CSS to create custom annotations. Alternatively, you can use online tools like VEED.IO, which provide easy-to-use annotation tools for videos.

How can I solve the “HTML5 video file not found” error?

Solving the “HTML5 video file not found” error involves identifying the cause of the error and addressing it. If the file path is incorrect, correct it. If the file has been deleted, restore it or replace it with a new file. If there are server issues, contact your server administrator or hosting provider for assistance. In some cases, the video file may be corrupted, in which case you would need to repair or replace the file.

Why is my HTML5 video not playing in Firefox?

If your HTML5 video is not playing in Firefox, it could be due to several reasons. Firefox may not support the video format specified in the source attribute of the

How can I repair a corrupted HTML5 video file?

Repairing a corrupted HTML5 video file involves using a video repair tool. These tools analyze the corrupted file and attempt to fix any errors or issues that are preventing the file from playing correctly. Some popular video repair tools include Stellar Video Repair and Wondershare Repairit.

How can I add controls to my HTML5 video?

You can add controls to your HTML5 video by including the controls attribute in the

Can I autoplay my HTML5 video?

Yes, you can autoplay your HTML5 video by including the autoplay attribute in the

How can I loop my HTML5 video?

You can loop your HTML5 video by including the loop attribute in the

Can I play multiple sources in my HTML5 video?

Yes, you can specify multiple sources for your HTML5 video by including multiple tags within the

Alexis GoldsteinAlexis Goldstein
View Author

Alexis Goldstein first taught herself HTML while a high school student in the mid-1990s, and went on to get her degree in Computer Science from Columbia University. She runs her own software development and training company, aut faciam LLC. Before striking out on her own, Alexis spent seven years in Technology on Wall Street, where she worked in both the cash equity and equity derivative spaces at three major firms, and learned to love daily code reviews. She is a teacher and a co-organizer of Girl Develop It, and a very proud member of the NYC Resistor hackerspace in Brooklyn, NY.

Estelle WeylEstelle Weyl
View Author

Estelle Weyl is a front-end engineer from San Francisco who has been developing standards-based accessible websites since 1999. She also writes two technical blogs with millions of visitors. Her passion is teaching web development so you'll find her speaking about CSS3, HTML5, JavaScript, and mobile web development at conferences around the United States.

Louis LazarisLouis Lazaris
View Author

Louis is a front-end developer, writer, and author who has been involved in the web dev industry since 2000. He blogs at Impressive Webs and curates Web Tools Weekly, a newsletter for front-end developers with a focus on tools.

bookbook excerptCSS3HTML5 Tutorials & Articles
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form