Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

HTMLMediaElement: `paused` and the `play`, `pause`, `ended`, and `error` events

Distinguish a media element’s current state from its events and from the result of calling `play()`. Tell a pause, natural completion, and a media resource failure apart.

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

Syntax

media.paused
media.ended
media.error
media.play() // Promise<void>
media.pause() // undefined
media.addEventListener("play", listener)
media.addEventListener("pause", listener)
media.addEventListener("ended", listener)
media.addEventListener("error", listener)

The web platform’s HTMLMediaElement interface serves audio and video elements; it is not part of ECMAScript. Its read-only boolean media.paused starts as true. A value of false means the element is not paused, but does not prove playback is advancing: the element may be waiting for data.

play() attempts to start or resume playback. It returns a promise that fulfills once playback has successfully started or rejects on failure, for example with NotAllowedError when autoplay policy blocks the request. The play event is queued when paused changes from true to false; it is not playing, which signals that playback is starting or resuming after waiting for data. pause() returns undefined and does not cause another pause transition if the element is already paused. The pause event is delivered after the element enters the paused state.

ended signals completion, not an ordinary pause. At the natural end of forward playback, pause can precede ended without a call to pause(); ended does not fire when loop === true and playbackRate is non-negative. The boolean media.ended is state, not an event.

Listen for these four events directly on the element: they do not bubble and are not cancelable. The error event signals a resource failure, such as a loading or decoding failure. Inspect media.error: it is a MediaError with a code, or null when no error is recorded. Handle play() rejection separately; an autoplay block alone is not a resource failure.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Media playback events</title>
</head>
<body>
  <audio id="media"></audio>
  <button id="start" type="button">Run media demo</button>
  <script>
    (() => {
      // Build one second of silent, unsigned 8-bit mono PCM WAV.
      const rate = 8000;
      const wav = new Uint8Array(44 + rate);
      const view = new DataView(wav.buffer);
      const text = (offset, value) => {
        for (let i = 0; i < value.length; i++) wav[offset + i] = value.charCodeAt(i);
      };
      text(0, "RIFF");
      view.setUint32(4, wav.length - 8, true);
      text(8, "WAVEfmt ");
      view.setUint32(16, 16, true);
      view.setUint16(20, 1, true);
      view.setUint16(22, 1, true);
      view.setUint32(24, rate, true);
      view.setUint32(28, rate, true);
      view.setUint16(32, 1, true);
      view.setUint16(34, 8, true);
      text(36, "data");
      view.setUint32(40, rate, true);
      wav.fill(128, 44);

      const media = document.getElementById("media");
      const start = document.getElementById("start");
      media.addEventListener("play", () => console.log(`play: paused=${media.paused}`));
      media.addEventListener("pause", () => console.log(`pause: paused=${media.paused}`));
      media.addEventListener("ended", () => {
        console.log(`ended: ended=${media.ended}`);
        media.src = "data:text/plain,not-a-media-file";
      }, { once: true });
      media.addEventListener("error", () => console.log(`error: code=${media.error?.code}`));

      start.addEventListener("click", async () => {
        start.remove();
        console.log(`paused=${media.paused}`);
        media.src = `data:audio/wav;base64,${btoa(String.fromCharCode(...wav))}`;
        try {
          await media.play();
        } catch (error) {
          console.log(`play() rejected: ${error.name}`);
        }
      }, { once: true });
    })();
  </script>
</body>
</html>

Result

paused=true
play: paused=false
pause: paused=true
ended: ended=true
error: code=4

Save the example as `media-demo.html` and open it in a browser. Open the browser console and click `Run media demo`. The expected sequence assumes PCM WAV support, permission to load `data:` media URLs, and uninterrupted playback. After one second of silence, natural completion produces `pause` before `ended`; only then does the code assign a deliberately invalid source. If `play()` rejects, inspect the rejection name rather than expecting the full sequence.

Related lessons

  • JavaScript · Lesson 34 · Advanced · Version: 4

Sources