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

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

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


当前回答

假设我们有流式视频标签,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;

其他回答

有溪流形式成功的参考吗

var streamRef;

var handleVideo = function (stream) {
    streamRef = stream;
}

//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
    val.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;

使用下列函数:

// 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();
        }
    });
}

如果.stop()已弃用,那么我认为我们不应该像@MuazKhan剂量那样重新添加它。这是一个原因,为什么东西被弃用,不应该再使用。只需创建一个辅助函数…这是一个更es6的版本

function stopStream (stream) {
    for (let track of stream.getTracks()) { 
        track.stop()
    }
}

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

MediaStream用法

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