HTML5 - Audio & Video
HTML5 - Audio & Video
Section titled “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.
Embedding Video (<video>)
Section titled “Embedding Video (<video>)”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.
Common <video> Attributes
Section titled “Common <video> Attributes”| Attribute | Description |
|---|---|
src | URL of the video file (alternative to using <source>). |
controls | Boolean attribute. If present, displays default browser playback controls. |
width | Width of the video player in CSS pixels. |
height | Height of the video player in CSS pixels. |
autoplay | Boolean 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). |
loop | Boolean attribute. Restarts the video from the beginning after it ends. |
muted | Boolean attribute. Mutes the audio output by default. |
poster | URL of an image to display before the video loads or while downloading. |
preload | Hints 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. |
playsinline | Boolean attribute. Important for iOS; allows video playback within the element’s bounds instead of forcing fullscreen. |
Embedding Audio (<audio>)
Section titled “Embedding Audio (<audio>)”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
.opusor.webm. - Vorbis: Open, royalty-free, good quality. Often in
.oggcontainer. - 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.
Common <audio> Attributes
Section titled “Common <audio> Attributes”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.
Controlling Media with JavaScript
Section titled “Controlling Media with JavaScript”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.
Key Methods & Properties
Section titled “Key Methods & Properties”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.
Key Events
Section titled “Key Events”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>Accessibility: Tracks (<track>)
Section titled “Accessibility: Tracks (<track>)”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>Server Configuration (MIME Types)
Section titled “Server Configuration (MIME Types)”Ensure your web server serves media files with the correct MIME types so browsers can identify them properly. Common types include:
MP4 Video: video/mp4WebM Video: video/webmMP3 Audio: audio/mpegOgg Audio: audio/oggOpus Audio: audio/opusWAV Audio: audio/wavVTT Tracks: text/vttConsult your web server’s documentation for instructions on how to configure MIME types (e.g., in .htaccess for Apache, or mime.types for Nginx).