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

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

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


当前回答

使用不同的浏览器启动网络摄像头视频

对于Opera 12

window.navigator.getUserMedia(param, function(stream) {
                            video.src =window.URL.createObjectURL(stream);
                        }, videoError );

Firefox夜间18.0

window.navigator.mozGetUserMedia(param, function(stream) {
                            video.mozSrcObject = stream;
                        }, videoError );

针对Chrome 22

window.navigator.webkitGetUserMedia(param, function(stream) {
                            video.src =window.webkitURL.createObjectURL(stream);
                        },  videoError );

使用不同浏览器停止摄像头视频

对于Opera 12

video.pause();
video.src=null;

Firefox夜间18.0

video.pause();
video.mozSrcObject=null;

针对Chrome 22

video.pause();
video.src="";

有了这个,网络摄像头的灯每次都要熄灭……

其他回答

试试下面的方法:

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

请检查这个:https://jsfiddle.net/wazb1jks/3/

导航器。getUserMedia(mediaConstraints,函数(流){ 窗口。streamReference =流; }, onMediaError);

停止记录

函数stopStream() { if (!window.streamReference)返回; window.streamReference.getAudioTracks () .forEach(函数(跟踪){ track.stop (); }); window.streamReference.getVideoTracks () .forEach(函数(跟踪){ track.stop (); }); 窗口。streamReference = null; }

有溪流形式成功的参考吗

var streamRef;

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

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