Sub topic 1
Embedding audio and video
Prerequisites
Assume you know basic HTML elements and attributes, including URLs and links. You should also understand how to create and serve files from a web page.
Embedding audio and video
HTML provides <audio> for sound and <video> for moving images. The controls attribute displays the browser's built-in playback controls.
<audio controls src="podcast.mp3">
<a href="podcast.mp3">Download the podcast</a>
</audio>
<video controls width="640" src="lesson.mp4">
<p><a href="lesson.mp4">Download the lesson video</a></p>
</video>The src attribute points directly to a media file. Relative URLs are resolved from the current page, while absolute URLs can point to another server. The server must return the file with a correct MIME type, such as audio/mpeg or video/mp4.
Containers and codecs
A container is a file format that packages the media streams and metadata. MP4 and WebM are common video containers. A codec is the algorithm used to compress and decompress a stream. For example, an MP4 file might contain H.264 video and AAC audio.
Browsers do not support every container and codec combination. Test the combinations you plan to publish.
| Container | Common codecs | Typical use |
|---|---|---|
| MP4 | H.264, AAC | Broad browser support |
| WebM | VP9, Opus | Modern web delivery |
Offering several formats with `source`
Use several <source> elements when you want the browser to choose a supported format. The browser checks them in order and uses the first format it can play.
<video controls width="640">
<source src="lesson.webm" type="video/webm">
<source src="lesson.mp4" type="video/mp4">
<p>Your browser cannot play this video.</p>
</video>The type attribute gives the browser a format hint. It can avoid downloading a source that the browser already knows it cannot use.
Fallback content is placed inside <audio> or <video>. Browsers that support the element usually ignore this content, while unsupported browsers can show its link or message.
Exercise
Why should a video usually include more than one source format?
Show answer
Different browsers support different container and codec combinations, so multiple sources improve compatibility.