HTML Audio/Video
Write code that pauses playback and reduces the audio volume to one half.
Understand the topic
Audio and video elements share the HTMLMediaElement interface. Properties include currentTime, duration, paused, muted, volume, and playbackRate. Methods include play(), pause(), and load(). Playback is asynchronous and can be rejected by browser policy, so handle the promise returned by play(). Wait for suitable metadata before relying on duration or seeking.
Worked example
const video = document.querySelector("video");
video.addEventListener("loadedmetadata", () => console.log(video.duration));
async function startPlayback() {
try {
await video.play();
} catch (error) {
console.log("Playback requires a supported source and an allowed user action.");
}
}
This source requires an actual video element with a valid media source. Connect startPlayback to a deliberate user control if you build a custom player.
Practice
Write code that pauses playback and reduces the audio volume to one half.
Show a suggested answer
video.pause();
video.volume = 0.5;Common mistake
Do not ignore play() rejections or replace native controls with inaccessible custom controls.