Sub topic 3
Controlling Media from JavaScript
Assume you know basic JavaScript, event listeners, promises, and async/await. The HTMLMediaElement API exposes properties and methods for controlling an <audio> or <video> element.
Controlling playback
Use play(), pause(), currentTime, volume, and muted. The example also uses a custom button that remains keyboard operable because it is a real <button>.
<video id="player" controls width="640" src="lesson.mp4"></video>
<button id="toggle" type="button" aria-pressed="false">Play</button>
<script>
const video = document.querySelector("#player");
const button = document.querySelector("#toggle");
button.addEventListener("click", async () => {
if (video.paused) {
try {
await video.play();
} catch (error) {
console.error("Playback failed:", error.name);
}
} else {
video.pause();
}
});
video.addEventListener("play", () => {
button.textContent = "Pause";
button.setAttribute("aria-pressed", "true");
});
video.addEventListener("pause", () => {
button.textContent = "Play";
button.setAttribute("aria-pressed", "false");
});
</script>The `play()` promise
play() returns a promise. The promise fulfills when playback starts and rejects when the browser blocks playback or cannot load the file. Always handle rejection, especially when starting media without a direct user action.
Media events and custom controls
Useful events include loadedmetadata, timeupdate, ended, play, and pause. Use loadedmetadata to read the duration and timeupdate to update a progress display. Custom controls need visible focus, clear labels, keyboard support, and captions where appropriate. Native controls are often safer when a custom design is unnecessary.
Formats and delivery
canPlayType() returns an empty string, maybe, or probably. It is a hint, not a guarantee.
const video = document.createElement("video");
console.log(video.canPlayType('video/webm; codecs="vp9, opus"'));The server must send the correct MIME type, such as video/mp4 or video/webm. It should also support byte-range requests so browsers can seek without downloading the entire file.
For media hosted on another origin, configure that server's CORS response headers and use crossorigin when needed. CORS does not convert an unsupported format into a supported one.
Adaptive streaming
For long or changing streams, Media Source Extensions (MSE) lets JavaScript append compatible media segments to a MediaSource object. MSE is a foundation for adaptive streaming, but it requires a segmenting and buffering strategy. Use a streaming library when you need manifest parsing, quality switching, and recovery logic.
Exercise
Why should code catch the promise returned by video.play()?
Show answer
The browser can reject it when autoplay is blocked or playback cannot start, so catching it prevents an unhandled rejection and lets the interface report the problem.