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

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

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


当前回答

有溪流形式成功的参考吗

var streamRef;

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

//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
    val.stop();
});

其他回答

你需要停止所有的轨迹(来自摄像头,麦克风):

localStream.getTracks().forEach(track => track.stop());

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

MediaStream用法

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

试试下面的方法:

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

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

对于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="";

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

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