Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

HTMLMediaElement events

Use nine audio and video events to keep playback position, duration, and controls in sync and to detect a resource reset, playback completion, or a media failure.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

media.addEventListener(type, (event) => { /* read event.currentTarget here */ });
// type: "timeupdate" | "loadedmetadata" | "durationchange" | "emptied"
//     | "play" | "pause" | "volumechange" | "ended" | "error"

HTMLMediaElement is the browser interface shared by audio and video elements, not part of ECMAScript. Use addEventListener() on the media element itself, ideally before setting src: these events do not bubble and cannot be canceled. In each handler, read the element's current state rather than trying to reconstruct it from event order.

loadedmetadata means metadata such as video dimensions is available, not that playback is ready. durationchange reports an initial or revised duration: duration is in seconds, with NaN when data is unavailable and Infinity when the end is unbounded. emptied means the resource state was reset, for example on a reload. Clear the old media details from the UI; the reset alone need not fire durationchange.

On timeupdate, read currentTime in seconds to refresh the position display. It can fire during playback or seeking; it is not a fixed-rate timer or a per-frame signal. play means paused became false, not that playback has started (playing). pause signals a transition to the paused state, not a temporary shortage of data. On volumechange, read both volume and muted: either can trigger it.

ended marks reaching the end, not an ordinary pause, though pause can also occur at the end. With loop set to true and a non-negative playbackRate, ended does not fire. On error, inspect media.error, for example media.error?.code; this MediaError concerns the media resource. Separately handle rejections of the play() promise: for example, NotAllowedError can reflect autoplay policy without firing a media error event.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>HTMLMediaElement events</title>
</head>
<body>
<script>
(() => {
  const panel = document.createElement('div');
  const audio = document.createElement('audio');
  audio.controls = true;
  audio.preload = 'metadata';
  panel.append(audio);

  // Generate three seconds of silence as mono, 8-bit PCM WAV.
  const rate = 8000;
  const samples = 3 * rate;
  const bytes = new Uint8Array(44 + samples);
  const view = new DataView(bytes.buffer);
  const tag = (offset, text) => bytes.set(new TextEncoder().encode(text), offset);
  const u16 = (offset, value) => view.setUint16(offset, value, true);
  const u32 = (offset, value) => view.setUint32(offset, value, true);
  tag(0, 'RIFF'); u32(4, 36 + samples); tag(8, 'WAVE');
  tag(12, 'fmt '); u32(16, 16); u16(20, 1); u16(22, 1);
  u32(24, rate); u32(28, rate); u16(32, 1); u16(34, 8);
  tag(36, 'data'); u32(40, samples); bytes.fill(128, 44);
  const wav = URL.createObjectURL(new Blob([bytes], { type: 'audio/wav' }));
  const bad = URL.createObjectURL(new Blob(['not audio'], { type: 'audio/wav' }));

  const listeners = new AbortController();
  const types = ['timeupdate', 'loadedmetadata', 'durationchange', 'emptied',
    'play', 'pause', 'volumechange', 'ended', 'error'];
  for (const type of types) {
    audio.addEventListener(type, ({ currentTarget: media }) => {
      console.log(type, {
        currentTime: media.currentTime, duration: media.duration,
        paused: media.paused, ended: media.ended,
        volume: media.volume, muted: media.muted,
        errorCode: media.error?.code ?? null
      });
    }, { signal: listeners.signal });
  }

  function button(label, action) {
    const control = document.createElement('button');
    control.type = 'button';
    control.textContent = label;
    control.addEventListener('click', action);
    panel.append(control);
  }
  button('Mute / unmute', () => { audio.muted = !audio.muted; });
  button('Reload', () => { audio.src = wav; });
  button('Load invalid audio', () => { audio.src = bad; });
  button('Remove demo', () => {
    listeners.abort();
    audio.removeAttribute('src');
    audio.load();
    panel.remove();
    URL.revokeObjectURL(wav);
    URL.revokeObjectURL(bad);
  });
  document.body.prepend(panel);
  audio.src = wav;
})();
</script>
</body>
</html>

Result

Expected observations, not a fixed transcript (each event name is logged with a state object):
- Initial load: durationchange and loadedmetadata; duration is 3 seconds at loadedmetadata.
- Play, pause, resume, and let the clip finish: play, timeupdate (repeated), pause, play again, and eventually ended. A pause event can also occur at the end.
- Mute / unmute: volumechange; muted toggles.
- Reload after metadata is available: emptied, then fresh durationchange and loadedmetadata.
- Load invalid audio: error with a non-null errorCode; emptied can appear first.

Save the example as an HTML file and open it in a browser that supports PCM WAV and allows `blob:` media. View the events in the developer console. Use the native controls to play and pause. The demo generates three seconds of silence without downloading a file; event timing and counts can vary. `Remove demo` removes the controls and releases the object URLs.

Related lessons

  • JavaScript · Lesson 28 · Intermediate · Version: 3

Sources