Sub topic 2
Controlling HTML Media Playback
Assume you know basic HTML, CSS sizing, and JavaScript event listeners. The audio and video elements share playback attributes. Use attributes for standard behavior before adding JavaScript.
Playback attributes
controlsdisplays the browser’s built-in controls.mutedstarts audio output at zero.looprestarts the media when it ends.autoplayrequests automatic playback.preload="metadata"asks the browser to load information such as duration, but not the whole file.playsinlinekeeps video inside the page on mobile browsers instead of forcing a full-screen player.
<video
controls
width="640"
poster="lesson-poster.jpg"
preload="metadata"
playsinline>
<source src="lesson.webm" type="video/webm">
<source src="lesson.mp4" type="video/mp4">
<track
kind="captions"
src="lesson.en.vtt"
srclang="en"
label="English"
default>
<p>
Your browser cannot play this video.
<a href="lesson.mp4">Download the video</a>.
</p>
</video>Sizing and poster images
The width attribute provides an intrinsic display width. CSS is usually better for responsive sizing:
video {
width: 100%;
max-width: 800px;
height: auto;
aspect-ratio: 16 / 9;
object-fit: contain;
background: #000;
}The poster image appears before playback begins. Use an image that identifies the video and has useful contrast. It is a preview, not a replacement for captions or a transcript.
Autoplay restrictions
Browsers commonly block autoplay when media has audible sound. This protects users from unexpected audio. Muted autoplay is more likely to work, but it should still be used only when it supports the page’s purpose.
Captions, subtitles, and accessibility
A track element connects a WebVTT text file to video. Captions include spoken words and important sounds for deaf or hard-of-hearing viewers. Subtitles usually translate spoken dialogue into another language.
Provide captions, visible keyboard-operable controls, clear labels, and a transcript or download link when practical. Do not rely on color alone to communicate playback state.
Exercise
Which attributes suit a decorative background video that should play silently and repeatedly?
Show answer
Use autoplay muted loop playsinline, and provide an accessible alternative if the video conveys information.