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

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

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


当前回答

试试下面的方法:

var mediaStream = null;
    navigator.getUserMedia(
        {
            audio: true,
            video: true
        },
        function (stream) {
            mediaStream = stream;
            mediaStream.stop = function () {
                this.getAudioTracks().forEach(function (track) {
                    track.stop();
                });
                this.getVideoTracks().forEach(function (track) { //in case... :)
                    track.stop();
                });
            };
            /*
             * Rest of your code.....
             * */
        });

    /*
    * somewhere insdie your code you call
    * */
    mediaStream.stop();

其他回答

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

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

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

MediaStream用法

使用stream.getTracks()。forEach(track => track.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();
        }
    });
}

当通过http连接时,在流上使用.stop()在chrome上工作。它在使用ssl (https)时不起作用。

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