我们的志愿者还没有将这篇文章翻译为 中文 (简体)。加入我们帮助完成翻译!
您也可以阅读此文章的English (US)版。
In short, the MediaStreamTrack
method stop()
method stops the track.
Syntax
MediaStreamTrack.stop();
Calling stop()
tells the user agent that the track's source—whatever that source may be, including files, network streams, or a local camera or microphone—is no longer needed by the MediaStreamTrack
. Since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped. It is instead disassociated from the track and the track object is stopped. Once no media tracks are using the source, the source may actually be completely stopped.
Immediately after calling stop()
, the track
state is set to ended
.
Example
In this example, we see a function which stops a streamed video by calling stop()
on every track on a given <video>
.
function stopStreamedVideo(videoElem) { let stream = videoElem.srcObject; let tracks = stream.getTracks(); tracks.forEach(function(track) { track.stop(); } videoElem.srcObject = null; }
This works by obtaining the video element's stream from its srcObject
property. Then the stream's track list is obtained by calling its getTracks()
method. From there, all that remains to do is to iterate over the track list using forEach()
and calling each track's stop()
method.
Finally, srcObject
is set to null
to sever the link to the MediaStream
object so it can be released.
Specifications
Specification | Status | Comment |
---|---|---|
Media Capture and Streams The definition of 'MediaStreamTrack.stop()' in that specification. |
Editor's Draft | Initial specification. |
Browser compatibility
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | 34 (34)[1] | No support | (Yes) | ? |
Feature | Android | Android Webview | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|---|
Basic support | ? | (Yes) | (Yes) | 34.0 (34) | No support | ? | ? | (Yes) |
[1] Prior to Firefox 52, only local tracks (that is, tracks obtained through getUserMedia()
) could be stopped. Now all kinds of tracks can be stopped, including those on a MediaStream
associated with a WebRTC connection, Web Audio API stream, or CanvasCaptureMediaStream
.
See also
MediaStreamTrack
, the interface it belongs to.MediaStreamTrack.readyState
ended