Audio & Video
Overview
Before HTML5, playing a video or audio file on the web was a nightmare. You had to force users to install third-party plugins like Adobe Flash.
Now, HTML has native `<audio>` and `<video>` tags. These tags allow the browser itself to play media files natively, providing built-in play/pause controls, volume sliders, and even subtitle support without requiring you to write any complex JavaScript.
Syntax
The `<video>` tag works similarly to an image, but it can play moving pictures.
Adding the `controls` attribute is crucial—without it, the video will just look like a static image and the user won't be able to click 'play'. The `poster` attribute shows a thumbnail image before the video starts playing.
<video controls width="640" poster="/thumbnail.jpg">
<!-- We provide multiple formats. The browser will try MP4 first. -->
<source src="/video/tutorial.mp4" type="video/mp4" />
<!-- If the browser doesn't support MP4, it tries WebM. -->
<source src="/video/tutorial.webm" type="video/webm" />
<!-- Fallback text if the browser is ancient -->
Your browser does not support the video tag.
</video>The `<audio>` tag is exactly the same, but for sound. Again, always include the `controls` attribute so the user gets a play button and volume slider.
<!-- Simple audio player -->
<audio controls>
<source src="/podcast/episode-1.mp3" type="audio/mpeg" />
<source src="/podcast/episode-1.ogg" type="audio/ogg" />
</audio>Accessibility is key! For deaf users or people watching in a noisy room, you should provide captions using the `<track>` tag inside your video.
<video controls>
<source src="/movie.mp4" type="video/mp4" />
<!-- English Subtitles -->
<track src="/subs/en.vtt" kind="subtitles" srclang="en" label="English" default />
<!-- Hindi Subtitles -->
<track src="/subs/hi.vtt" kind="subtitles" srclang="hi" label="Hindi" />
</video>Common Pitfalls
- Browsers have strict rules about Auto-playing media. You CANNOT auto-play a video with sound. If you want a video to autoplay, you MUST include the 'muted' attribute.
- Always provide multiple <source> formats (MP4 and WebM for video) to ensure it works across all devices, including old Safari browsers.
Real-World Example
An auto-playing, muted background video for a landing page hero section:
<div class="hero-section">
<!-- autoplay: starts immediately
muted: required by browsers for autoplay to work
loop: starts over when finished
playsinline: required for iPhones to play without full-screening -->
<video
autoplay
muted
loop
playsinline
class="background-video"
>
<source src="/assets/hero-bg.mp4" type="video/mp4" />
</video>
<div class="hero-content">
<h1>Welcome to the Future</h1>
</div>
</div>