Skip to content

HTML5 - Audio & Video

One of the major advancements in HTML5 was the introduction of the <audio> and <video> elements, providing a standard, plugin-free way to embed and control multimedia content directly within web pages.

This eliminated the previous reliance on third-party plugins like Adobe Flash or Microsoft Silverlight (which are now obsolete) for basic media playback.

The <video> element embeds video content. At its simplest, you provide the video source using the src attribute and optionally include the controls attribute to display the browser’s default playback controls (play/pause, volume, fullscreen, etc.).

<!DOCTYPE html>
<html>
<head>
<title>Simple Video Example</title>
</head>
<body>
<h1>My Awesome Video</h1>
<video src="videos/myvideo.mp4" width="640" height="360" controls>
<!-- Fallback content for older browsers -->
Sorry, your browser doesn't support embedded videos.
You can <a href="videos/myvideo.mp4">download the video</a> instead.
</video>
</body>
</html>

Using the <source> Element for Multiple Formats

Section titled “Using the <source> Element for Multiple Formats”

Different browsers historically supported different video formats (codecs and containers). To ensure broader compatibility, it’s best practice to provide multiple video formats using nested <source> elements within the <video> tag. The browser will use the first format it understands.

Common web video formats include:

  • MP4 (H.264 + AAC): Widely supported, good balance of quality and compression. Often the primary choice.
  • WebM (VP8/VP9 + Vorbis/Opus): Open and royalty-free format, excellent quality, well-supported in Chrome/Firefox/Edge.
  • AV1 (with Opus/other audio): Newer, royalty-free codec offering superior compression, gaining support.
<video width="640" height="360" controls poster="images/video-poster.jpg">
<source src="videos/myvideo.webm" type="video/webm">
<source src="videos/myvideo.mp4" type="video/mp4">
<!-- Add more sources if needed (e.g., AV1) -->
<!-- Fallback content -->
Sorry, your browser doesn't support embedded videos.
</video>

The type attribute in <source> helps the browser quickly determine if it can play the format without downloading it first.

AttributeDescription
srcURL of the video file (alternative to using <source>).
controlsBoolean attribute. If present, displays default browser playback controls.
widthWidth of the video player in CSS pixels.
heightHeight of the video player in CSS pixels.
autoplayBoolean attribute. Starts playing the video automatically as soon as possible. Note: Most modern browsers restrict autoplay with sound unless the user has interacted with the site or the video is muted (muted attribute).
loopBoolean attribute. Restarts the video from the beginning after it ends.
mutedBoolean attribute. Mutes the audio output by default.
posterURL of an image to display before the video loads or while downloading.
preloadHints to the browser how much of the video file should be loaded when the page loads. Values: none (don’t preload), metadata (load only metadata like duration), auto (browser decides, may load entire video). Ignored if autoplay is present.
playsinlineBoolean attribute. Important for iOS; allows video playback within the element’s bounds instead of forcing fullscreen.

The <audio> element works very similarly to <video>, but is used for sound content.

<audio controls>
<source src="audio/mysound.opus" type="audio/opus">
<source src="audio/mysound.ogg" type="audio/ogg; codecs=vorbis">
<source src="audio/mysound.mp3" type="audio/mpeg">
<!-- Fallback content -->
Your browser does not support the audio element.
</audio>

Common web audio formats:

  • MP3: Very widely supported, but patent-encumbered.
  • Opus: Open, royalty-free, highly efficient codec, excellent for both music and speech. Often containerized in .opus or .webm.
  • Vorbis: Open, royalty-free, good quality. Often in .ogg container.
  • AAC: Good quality, common (especially with MP4 video), but patent-encumbered.
  • WAV: Uncompressed, high quality, large file size. Not ideal for web streaming but sometimes used for short sound effects.

Most attributes are similar to <video>: src, controls, autoplay, loop, muted, preload. Width and height are generally not applicable. The <source> element is used identically for providing multiple formats.

The HTMLMediaElement API (which both <audio> and <video> implement) provides rich JavaScript methods, properties, and events to control playback, check status, and respond to media events.

  • play(): Starts or resumes playback.
  • pause(): Pauses playback.
  • load(): Resets the media element and restarts loading the media source.
  • currentTime: Get or set the current playback position (in seconds).
  • duration: Read-only. Returns the total length of the media (in seconds).
  • volume: Get or set the audio volume (0.0 to 1.0).
  • muted: Get or set the muted state (boolean).
  • paused: Read-only boolean indicating if playback is paused.
  • ended: Read-only boolean indicating if playback has finished.
  • seeking: Read-only boolean indicating if a seek operation is in progress.
  • networkState, readyState: Provide information about the loading status.
  • play, pause, ended, timeupdate, volumechange, seeking, seeked, canplay, canplaythrough, loadeddata, error, progress, waiting (buffering).

JavaScript Example: Custom Play/Pause Button

Section titled “JavaScript Example: Custom Play/Pause Button”
<!DOCTYPE html>
<html>
<head>
<title>JS Media Control</title>
</head>
<body>
<video id="myPlayer" width="640" height="360" src="videos/myvideo.mp4"></video>
<div>
<button id="playPauseBtn">Play</button>
</div>
<script>
const player = document.getElementById('myPlayer');
const playPauseBtn = document.getElementById('playPauseBtn');
function togglePlayPause() {
if (player.paused || player.ended) {
player.play();
} else {
player.pause();
}
}
playPauseBtn.addEventListener('click', togglePlayPause);
// Update button text based on player state
player.addEventListener('play', () => { playPauseBtn.textContent = 'Pause'; });
player.addEventListener('pause', () => { playPauseBtn.textContent = 'Play'; });
player.addEventListener('ended', () => { playPauseBtn.textContent = 'Play'; });
</script>
</body>
</html>

The <track> element, nested within <audio> or <video>, is used to specify timed text tracks like subtitles, captions, descriptions, chapters, or metadata. This is crucial for accessibility.

<video controls width="640" height="360">
<source src="videos/myvideo.mp4" type="video/mp4">
<track kind="subtitles" src="subtitles/myvideo-en.vtt" srclang="en" label="English" default>
<track kind="captions" src="captions/myvideo-es.vtt" srclang="es" label="Español">
<!-- VTT (Web Video Text Tracks) is a common format -->
Sorry, your browser doesn't support embedded videos.
</video>

Ensure your web server serves media files with the correct MIME types so browsers can identify them properly. Common types include:

MP4 Video: video/mp4
WebM Video: video/webm
MP3 Audio: audio/mpeg
Ogg Audio: audio/ogg
Opus Audio: audio/opus
WAV Audio: audio/wav
VTT Tracks: text/vtt

Consult your web server’s documentation for instructions on how to configure MIME types (e.g., in .htaccess for Apache, or mime.types for Nginx).