15. Embedding Audio and Video
HTML5 introduced standard elements for embedding media without relying on third-party plugins (like Flash).
15.1 The Video Element (<video>)
The <video> element embeds a video file. It typically uses the controls attribute to display standard playback buttons.
html <video width="640" height="360" controls> <source src="assets/intro-video.mp4" type="video/mp4"> <source src="assets/intro-video.webm" type="video/webm"> <!-- Fallback text if the browser doesn't support the video element --> Your browser does not support the video tag. </video>
Why multiple <source> tags?
Browsers support different video formats (MP4, WebM, OGG). Providing multiple sources ensures compatibility. The browser will try them in order until it finds one it can play.
15.2 The Audio Element (<audio>)
The <audio> element works similarly but doesn't need width/height specifications.
html <audio controls> <source src="assets/background-music.mp3" type="audio/mp3"> <source src="assets/background-music.ogg" type="audio/ogg"> Your browser does not support the audio element. </audio>
15.3 Important Attributes
| Attribute | Description |
|---|---|
controls | Displays the player controls (play/pause, volume, etc.). |
autoplay | Automatically starts playing the media (often blocked by browsers). |
loop | Causes the media to restart automatically when finished. |
muted | Silences the audio output by default. |