MediaStream

Signature

const stream = new MediaStream();              // empty
const stream = new MediaStream(tracks);        // from an array of tracks
const stream = new MediaStream(existingStream); // clone the track set

What it does

Groups one or more MediaStreamTrack objects so they can be attached to a <video>/<audio> element or added to an RTCPeerConnection together.

Key members

Member Kind Purpose
id property Unique stream identifier.
active property true while at least one track is live.
getTracks() method All tracks in the stream.
getAudioTracks() / getVideoTracks() method Tracks of one kind.
addTrack() / removeTrack() method Add or remove a track.
getTrackById() method Look up a track by its id.
addtrack / removetrack event Fires when the track set changes.

Behaviour & constraints

  • A stream is a container; stopping it does nothing: you stop individual tracks via track.stop().
  • The same track can belong to multiple streams at once.
  • getUserMedia() and getDisplayMedia() return a MediaStream.
  • Assign to video.srcObject rather than src to play it.
  • active becomes false only after every track has ended.

Example

const stream = await navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true,
});
video.srcObject = stream;

for (const track of stream.getTracks()) {
  pc.addTrack(track, stream);
}

See also