Sub topic 1
Embedding audio and video
Prerequisites
This chapter assumes you know the following:
- Basic HTML document structure and attributes.
- Basic CSS for sizing and layout.
- Basic JavaScript: selecting elements and adding event listeners.
Promises and async/await appear in later chapters. You do not need them here.
What the media elements do
HTML has two elements for embedding time-based media: <audio> and <video>. Both load a media file, decode it, and play it without a plugin. Both share one interface in JavaScript, called HTMLMediaElement. Most of what you learn about one applies to the other.
The main difference is visual. <video> renders a picture area. <audio> has no picture area, so it shows nothing unless you ask for the browser's controls.
Neither element is a file viewer. Each is a small playback engine that the browser configures from your attributes. The browser fetches the file, reads its metadata, decodes frames or samples, and sends them to the screen and speakers.
The simplest audio embed
The controls attribute tells the browser to draw its built-in player. Without it, an <audio> element is invisible and silent until a script starts it.
<audio controls src="podcast-episode.mp3">
<a href="podcast-episode.mp3">Download the episode</a>
</audio>The src attribute points at the file. The link inside the element is fallback content. A browser that supports <audio> ignores it. A browser that does not shows the link instead.
The simplest video embed
A video works the same way, with a few extra attributes for its picture area.
<video controls width="640" src="clip.mp4"></video>Setting width (and ideally height) reserves space before the file loads. Without it, the page layout can jump when the video's dimensions become known. Chapter topics on sizing and posters come later. For now, treat width as a good habit.
Pointing an element at a file
The src attribute takes a URL. It can be relative or absolute, like the src of an image.
<video controls src="media/lesson-1.mp4"></video>
<video controls src="https://example.com/media/lesson-1.mp4"></video>The browser does not download the whole file before playing. It requests the beginning, reads the metadata, and starts playback while the rest arrives. That is why the file's structure and the server's behavior matter. Later chapters cover both.
A single src has a weakness. It names exactly one file, in exactly one format. If the browser cannot play that format, nothing plays. The next section explains why that happens.
Containers and codecs
A media file is two layers.
- A container is the file format that packages the streams together. Examples are MP4, WebM, and Ogg. The container holds video, audio, subtitles, and timing data.
- A codec (short for coder-decoder) is the method used to compress and decompress one stream. Examples are H.264 and VP9 for video, and AAC, MP3, and Opus for audio.
A file named clip.mp4 tells you the container, but not which codecs are inside. A browser needs to support both the container and every codec in it.
| Container | Common video codecs | Common audio codecs |
|---|---|---|
| MP4 | H.264, H.265, AV1 | AAC, MP3 |
| WebM | VP8, VP9, AV1 | Vorbis, Opus |
| Ogg | Theora | Vorbis, Opus |
| MP3 (audio only) | none | MP3 |
Support differs between browsers and operating systems. H.264 with AAC in MP4 is the widest choice. VP9 with Opus in WebM is a common alternative that often gives smaller files. Check current browser support tables before you commit to a format, because support changes.
Offering several formats with source
To let the browser pick a format it can play, drop the src attribute and list <source> children. The browser reads them in order and uses the first one it supports.
<video controls width="640" poster="poster.jpg" preload="metadata">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<track kind="captions" src="clip.en.vtt" srclang="en" label="English" default>
<p>Your browser cannot play this video. <a href="clip.mp4">Download it instead</a>.</p>
</video>Points to notice:
- Order expresses preference. Here the WebM file is tried first, and MP4 is the safety net.
- The
typeattribute lets the browser skip a source without downloading it. If you omittype, the browser may have to fetch part of the file to find out whether it can play it. - Put a
codecsparameter intypewhen the choice depends on it, for exampletype='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'. Use single quotes around the attribute value when the value contains double quotes. <source>is a void element. It has no closing tag.- If an element has a
srcattribute, the browser ignores its<source>children. Use one approach or the other.
Fallback content
Anything inside the element that is not a <source> or <track> is fallback content. Only browsers that do not understand the element render it. Modern browsers all support <audio> and <video>, so this content rarely appears.
Two details cause confusion:
- Fallback content does not appear when the browser supports the element but cannot play your formats. In that case the player shows an error state, and your paragraph stays hidden.
- A download link is still worthwhile. Assistive tools and old embedded browsers may read it. Screen reader users also sometimes prefer the file.
If you need to react to a playback failure, listen for the error event on the element, or on the last <source>. A later chapter covers events.
A first look at playback attributes
Attributes on the element shape its behavior. Later chapters examine each one. This table is only a preview.
| Attribute | Effect |
|---|---|
| `controls` | Shows the browser's built-in controls |
| `loop` | Restarts when playback ends |
| `muted` | Starts silent |
| `autoplay` | Tries to start as soon as possible |
| `preload` | Hints how much to download before the user plays |
| `playsinline` | Plays inside the page on iOS instead of full screen |
Here is a common pattern for decorative background video:
<video autoplay muted loop playsinline src="background.mp4"></video>Browsers restrict autoplay because unexpected sound is a poor experience. A muted, inline video is the case they most commonly allow. Do not rely on autoplay for anything the user must see or hear.
Common errors
- Wrong format for the browser. The file plays on your machine but not elsewhere. Offer two formats with
<source>, and check the codecs inside the container, not only the extension. - No
controlsand no script. The element exists but nothing visible appears, especially for<audio>. Addcontrols. - Both
srcand<source>children. The children are ignored. Choose one. - Missing
type. The browser may download extra data to test each source. Addtype. - No size on video. The page shifts as the video loads. Set
widthandheight, or use CSSaspect-ratio. - Expecting fallback text to show on a format failure. It does not. Detect failure with the
errorevent. - Autoplay with sound. It is usually blocked. Start playback from a user action instead.
Putting it together
This page embeds an audio episode and a video, each with a fallback.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Media demo</title>
</head>
<body>
<h1>Episode 1</h1>
<audio controls preload="none">
<source src="episode1.opus" type="audio/ogg; codecs=opus">
<source src="episode1.mp3" type="audio/mpeg">
<a href="episode1.mp3">Download the episode</a>
</audio>
<video controls width="640" height="360" poster="poster.jpg" preload="metadata">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<p><a href="clip.mp4">Download the video</a>.</p>
</video>
</body>
</html>The audio uses preload="none", so the browser fetches nothing until the user presses play. The video uses preload="metadata", so the browser fetches only the duration and dimensions.
Exercise
A page has <video controls src="a.webm"><source src="b.mp4" type="video/mp4"></video>. A browser that cannot play WebM visits it. Does it play b.mp4? Explain, and describe how to fix the markup.
Show answer
No. When the element has a src attribute, the browser ignores its <source> children, so it only tries a.webm and fails. Remove src from the <video> tag and list both files as <source> elements, each with a type, for example <source src="a.webm" type="video/webm"> followed by <source src="b.mp4" type="video/mp4">.
Exercise
Why does a download link placed inside <audio> not show up when the browser supports <audio> but cannot decode your file?
Show answer
Fallback content is shown only by browsers that do not recognize the element. A browser that supports the element shows its own player, in an error state, and hides the children. To handle a decode failure, listen for the error event or provide a download link outside the element.