我使用以下JavaScript代码打开了一个网络摄像头:

const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });

是否有任何JavaScript代码停止或关闭网络摄像头?


当前回答

FF, Chrome和Opera已经开始通过导航器公开getUserMedia。mediaDevices现在是标准(可能会改变:)

在线演示

navigator.mediaDevices.getUserMedia({audio:true,video:true})
    .then(stream => {
        window.localStream = stream;
    })
    .catch( (err) =>{
        console.log(err);
    });
// later you can do below
// stop both video and audio
localStream.getTracks().forEach( (track) => {
track.stop();
});
// stop only audio
localStream.getAudioTracks()[0].stop();
// stop only video
localStream.getVideoTracks()[0].stop();

其他回答

使用下列函数:

// stop both mic and camera
function stopBothVideoAndAudio(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live') {
            track.stop();
        }
    });
}

// stop only camera
function stopVideoOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'video') {
            track.stop();
        }
    });
}

// stop only mic
function stopAudioOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'audio') {
            track.stop();
        }
    });
}

FF, Chrome和Opera已经开始通过导航器公开getUserMedia。mediaDevices现在是标准(可能会改变:)

在线演示

navigator.mediaDevices.getUserMedia({audio:true,video:true})
    .then(stream => {
        window.localStream = stream;
    })
    .catch( (err) =>{
        console.log(err);
    });
// later you can do below
// stop both video and audio
localStream.getTracks().forEach( (track) => {
track.stop();
});
// stop only audio
localStream.getAudioTracks()[0].stop();
// stop only video
localStream.getVideoTracks()[0].stop();

假设我们有流式视频标签,id是video - <video id="video"></video>,那么我们应该有以下代码-

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

不要使用stream.stop(),它已被弃用

MediaStream用法

使用stream.getTracks()。forEach(track => track.stop())

因为这个答案是最初发布的浏览器API已经改变了。 .stop()在传递给回调函数的流上不再可用。 开发者必须访问组成流的音轨(音频或视频)并分别停止它们。

更多信息请访问:https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active

示例(来自上面的链接):

stream.getTracks () .forEach(函数(跟踪){ track.stop (); });

浏览器支持可能有所不同。

以前,导航器。getUserMedia在成功回调中为您提供了一个流,您可以在该流上调用.stop()来停止录制(至少在Chrome中,似乎FF不喜欢它)