MediaStream: removeTrack() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
TheremoveTrack() method of theMediaStream interface removes aMediaStreamTrack from a stream.
In this article
Syntax
js
removeTrack(track)Parameters
trackA
MediaStreamTrackthat will be removed from the stream.
Return value
None (undefined).
Examples
The following example demonstrates how to remove the audio and video tracks from aMediaStream.fetchStreamFunction is an event handler forfetchStreamButton. When the button is clicked, audioand video are captured from the system's devices.removeTracksFunction is the event handler forremoveTracksButton.When this button is clicked, the audio and video tracks are removed from theMediaStream.
js
let initialStream = null;let newStream = null;let fetchStreamButton = document.getElementById("fetchStream");let removeTracksButton = document.getElementById("removeTracks");async function fetchStreamFunction() { initialStream = await navigator.mediaDevices.getUserMedia({ video: { width: 620, height: 310 }, audio: true, }); if (initialStream) { await attachToDOM(initialStream); }}async function attachToDOM(stream) { newStream = new MediaStream(stream.getTracks()); document.querySelector("video").srcObject = newStream;}async function removeTracksFunction() { let videoTrack = newStream.getVideoTracks()[0]; let audioTrack = newStream.getAudioTracks()[0]; newStream.removeTrack(videoTrack); newStream.removeTrack(audioTrack); // Stream will be empty console.log(newStream.getTracks());}fetchStreamButton.addEventListener("click", fetchStreamFunction);removeTracksButton.addEventListener("click", removeTracksFunction);Specifications
| Specification |
|---|
| Media Capture and Streams> # dom-mediastream-removetrack> |