Skip to content
Tutorials Center
My learning

Topics

HTML Reference Β· Images and Media

Audio and video DOM reference

The audio and video DOM API: HTMLMediaElement properties, play(), pause(), load(), canPlayType(), media events, readyState and networkState values.

Every <audio> and <video> element is an HTMLMediaElement in the DOM (more precisely an HTMLAudioElement or HTMLVideoElement). Its properties tell you where playback is and what has loaded, its methods start and stop playback, and its events tell you when something changes. With them you can build custom controls, sync captions or animations to the playhead, or react when a clip ends.

JavaScript
const video = document.querySelector("video");
video.currentTime = 30;          // jump to 0:30
await video.play();              // returns a promise
video.addEventListener("ended", () => console.log("done"));

Try it

Custom video controls

The play button only asks to play; the label changes in the play and pause event handlers, so it stays correct even when playback stops because the clip ended. play() returns a promise that rejects (for example with NotAllowedError when autoplay rules block sound), so the code catches it.

Properties

Source and loading

Property Type Description
src String The src attribute. Setting it starts loading a new resource.
currentSrc String, read-only The absolute URL of the resource actually chosen (useful with several <source> children). Empty until one is selected.
srcObject MediaStream, MediaSource or Blob A live source such as a webcam stream from getUserMedia(). Takes priority over src.
crossOrigin String or null Reflects the crossorigin attribute.
preload String Reflects preload: "none", "metadata" or "auto".
networkState Number, read-only The loading state (see the table below).
readyState Number, read-only How much data is available to play (see the table below).
buffered TimeRanges, read-only The time ranges that have been downloaded.
error MediaError or null The last error: error.code (1–4) and error.message.

Playback

Property Type Description
currentTime Number (seconds) The playhead position. Setting it seeks.
duration Number, read-only The length in seconds. NaN before metadata has loaded; Infinity for live streams.
paused Boolean, read-only true unless playing (or trying to play). Starts as true.
ended Boolean, read-only true when playback reached the end (and loop is off).
seeking Boolean, read-only true while a seek is in progress.
playbackRate Number The speed: 1 is normal, 0.5 half, 2 double. Negative values are not supported by every browser.
defaultPlaybackRate Number The rate restored after load(). Default 1.
preservesPitch Boolean Keep the pitch of the audio when the rate changes. Default true.
played TimeRanges, read-only The ranges that have actually been played.
seekable TimeRanges, read-only The ranges the user can seek to.
loop, autoplay, controls Boolean Reflect the attributes of the same names.

Sound

Property Type Description
volume Number, 0–1 The volume. Values outside the range throw an error. On iOS it is read-only and always 1.
muted Boolean Whether the sound is muted, independently of volume.
defaultMuted Boolean Reflects the muted attribute, which only sets the initial state.

Tracks and video only

Property Description
textTracks A TextTrackList of the captions, subtitles and chapters from <track> elements. Set track.mode to "showing", "hidden" or "disabled".
audioTracks, videoTracks Lists of the tracks inside the file. Supported only by Safari, so don't rely on them.
videoWidth, videoHeight (<video>) The video's real pixel size, 0 before metadata is loaded.
poster (<video>) Reflects the poster attribute.
playsInline (<video>) Reflects playsinline.

Methods

Method Returns Description
play() Promise<void> Starts or resumes playback. The promise resolves when playback starts and rejects with NotAllowedError (autoplay blocked), NotSupportedError (no playable source) or AbortError (interrupted by pause() or load()).
pause() undefined Pauses playback.
load() undefined Resets the element and selects a source again. Call it after changing <source> children; setting src does this automatically.
canPlayType(type) "", "maybe" or "probably" Whether the browser can likely play a MIME type, optionally with codecs: 'video/mp4; codecs="avc1.42E01E"'. "" means no.
fastSeek(time) undefined Seeks quickly to the nearest keyframe instead of the exact time. Supported in Firefox and Safari; use currentTime elsewhere.
addTextTrack(kind, label, language) TextTrack Creates a text track from script, to which you add VTTCue objects.
setSinkId(id) Promise Sends audio to a specific output device. Not supported in every browser.
requestPictureInPicture() Promise (<video>) Opens the video in a floating window. Needs a user gesture.
requestVideoFrameCallback(cb) Number (<video>) Calls cb when the next frame is shown; good for frame-accurate canvas effects.
What can this browser play?

A container type such as video/mp4 without a codecs parameter usually gets "maybe", because the container alone doesn't say which codecs are inside; adding codecs lets the browser answer "probably". The made-up type gets an empty string. The answers differ between browsers and devices, which is why lists of <source> elements exist.

Events

Media events are sent to the media element and don't bubble, so listen on the element itself (or use a capturing listener on an ancestor). Each one also has an on… event attribute.

Event Fires when
loadstart The browser starts looking for or loading the resource.
durationchange duration changes, usually once the metadata arrives.
loadedmetadata Duration and dimensions are known (readyState reaches 1).
loadeddata The frame at the current position is available (readyState reaches 2).
canplay Playback can start, but may have to pause to buffer (readyState 3).
canplaythrough Playback can probably reach the end without buffering (readyState 4).
progress More data was downloaded (fires periodically).
suspend Downloading paused on purpose, for example because enough is buffered or preload asked for little.
stalled Data is expected but has not arrived for a while.
waiting Playback stopped because the next frame isn't loaded yet.
play paused changed to false after play() or the autoplay attribute.
playing Playback actually started (also after buffering).
pause Playback was paused.
timeupdate currentTime changed: several times a second while playing, and on seeks.
seeking, seeked A seek started and finished.
ratechange playbackRate or defaultPlaybackRate changed.
volumechange volume or muted changed.
resize (<video>) videoWidth or videoHeight changed.
ended Playback reached the end (not fired when loop is on).
emptied The element was reset, for example by load() during loading.
abort Loading was stopped before it finished, but not because of an error.
error Loading failed; details are in element.error.

When a page loads a video with preload="auto", the usual order is loadstart, durationchange, loadedmetadata, loadeddata, canplay, canplaythrough, with progress and suspend in between.

State constants

readyState

Value Constant Meaning
0 HAVE_NOTHING Nothing is known about the media yet.
1 HAVE_METADATA Duration and dimensions are known; no frame data yet. Seeking is possible.
2 HAVE_CURRENT_DATA Data for the current position exists, but not for the next moment.
3 HAVE_FUTURE_DATA Enough data to play forward a little.
4 HAVE_ENOUGH_DATA Enough data to play to the end without stopping, judging by the download speed.

networkState

Value Constant Meaning
0 NETWORK_EMPTY Not initialized; no source has been chosen.
1 NETWORK_IDLE A source is chosen, but the browser isn't downloading right now.
2 NETWORK_LOADING Downloading.
3 NETWORK_NO_SOURCE No supported source was found.

MediaError.code

Value Constant Meaning
1 MEDIA_ERR_ABORTED The user or script stopped the download.
2 MEDIA_ERR_NETWORK A network error happened after the resource was found to be usable.
3 MEDIA_ERR_DECODE The file is damaged or uses features the decoder can't handle.
4 MEDIA_ERR_SRC_NOT_SUPPORTED The source is unusable: a missing file, a wrong URL or an unsupported format.

All of these constants also exist as static properties, so you can compare with video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA instead of a bare number.

Event log with readyState and networkState

Play, pause, seek or change the volume in the built-in controls and watch the new events appear. The loading events at the start appear in the order of rising readyState.

Errors and time ranges

Loading the missing file fails with code 4, MEDIA_ERR_SRC_NOT_SUPPORTED, and networkState becomes 3 (NETWORK_NO_SOURCE): to the media element, a 404 page is simply a source it can't use. A TimeRanges object is not an array; read it with length, start(i) and end(i).

Usage notes

  • Always handle the play() promise. An unhandled rejection shows up as an error in the console. Catch it and show a play button, or start muted.
  • Autoplay rules. Browsers allow playback without a user gesture only when the media is muted (or the user has interacted with the site). Calling play() inside a click handler always counts as a gesture.
  • Use events for UI state. Update buttons in play/pause/ended handlers instead of right after calling a method, because playback can start, stop or fail on its own.
  • duration can be NaN. Wait for loadedmetadata before reading it or the video's size.
  • timeupdate is coarse. It fires about 4 to 66 times per second depending on the browser. For smooth progress bars or frame-accurate work, read currentTime in requestAnimationFrame() or use requestVideoFrameCallback().
  • Custom controls must stay accessible. Use real <button> and <input type="range"> elements with labels, as in the first example, so keyboard and screen-reader users can operate them.
  • Media Session API. navigator.mediaSession lets you set the title, artwork and hardware media-key handlers shown by the operating system.

Browser support

HTMLMediaElement and the events above are supported in every browser. fastSeek(), audioTracks/videoTracks, setSinkId() and requestVideoFrameCallback() are not available everywhere; codec support (canPlayType()) varies by browser and platform.