HTML Media
HTML5 ships with first-class media elements -
Video and audio in HTML5
EXAMPLE
<!-- Basic video with multiple sources -->
<video controls width='640' height='360' poster='/poster.jpg' preload='metadata'>
<source src='/clip.mp4' type='video/mp4' />
<source src='/clip.webm' type='video/webm' />
<!-- Captions for accessibility (WebVTT format) -->
<track kind='captions' srclang='en' label='English' src='/clip.en.vtt' default />
<track kind='captions' srclang='es' label='Espanol' src='/clip.es.vtt' />
<p>Your browser does not support video. <a href='/clip.mp4'>Download it</a>.</p>
</video>
<!-- Audio with fallback -->
<audio controls preload='none'>
<source src='/podcast.mp3' type='audio/mpeg' />
<source src='/podcast.ogg' type='audio/ogg' />
Your browser does not support audio.
</audio>
<!-- Programmatic control -->
<script>
const v = document.querySelector('video');
v.addEventListener('play', () => console.log('playing'));
v.addEventListener('pause', () => console.log('paused'));
v.addEventListener('ended', () => console.log('done'));
// Methods
// v.play(); v.pause(); v.currentTime = 30; v.playbackRate = 1.5;
</script>
<!-- Responsive aspect ratio (no JS) -->
<style>
.video-wrap {
aspect-ratio: 16 / 9;
max-width: 100%;
background: #000;
}
.video-wrap video { width: 100%; height: 100%; object-fit: contain; }
</style>
<!-- Picture element for art direction (not just video) -->
<picture>
<source media='(min-width: 1024px)' srcset='/hero-wide.jpg' />
<source media='(min-width: 768px)' srcset='/hero-mid.jpg' />
<img src='/hero-mobile.jpg' alt='Hero' loading='lazy' />
</picture>
Why it matters
Use multiple
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Media</title>
</head>
<body>
<h1>HTML Media</h1>
<p>This is a demo page for the "HTML Media" lesson.</p>
</body>
</html>
Try it Yourself »
Exercise
Add the attribute that gives the user play/pause/volume controls on the player.
<video src="clip.mp4"
></video>
A boolean attribute — just its name.
Discussion
Loading…