停止/关闭由navigator.getUserMedia打开的网络摄像头

时间:2022-06-22 02:23:15

I opened a webcam by using the following JavaScript code: navigator.getUserMedia

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

Is there any JavaScript code to stop or close the webcam? Thanks everyone.

是否有任何JavaScript代码可以停止或关闭网络摄像头?感谢大家。

11 个解决方案

#1


94  

EDIT

编辑

Since this answer has been originally posted the browser API has changed. .stop() is no longer available on the stream that gets passed to the callback. The developer will have to access the tracks that make up the stream (audio or video) and stop each of them individually.

由于此答案最初发布,因此浏览器API已更改。 .stop()在传递给回调的流上不再可用。开发人员必须访问组成流(音频或视频)的曲目并单独停止每个曲目。

More info here: https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active

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

Example (from the link above):

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

var track = stream.getTracks()[0];  // if only one media track
// ...
track.stop();

Browser support may differ.

浏览器支持可能不同。

Original answer

原始答案

navigator.getUserMedia provides you with a stream in the success callback, you can call .stop() on that stream to stop the recording (at least in Chrome, seems FF doesn't like it)

navigator.getUserMedia为您提供成功回调中的流,您可以在该流上调用.stop()来停止录制(至少在Chrome中,似乎FF不喜欢它)

#2


46  

You can call "stop" over MediaStream object which is going to be obsolete; new proposal is to release media tracks by calling "stop" over each media track:

你可以在MediaStream对象上调用“stop”,这个对象将会过时;新提案是通过在每个媒体轨道上调用“停止”来发布媒体曲目:

mediaStream.stop();

// or
mediaStream.getAudioTracks()[0].stop();
mediaStream.getVideoTracks()[0].stop();

Updated at Nov 03, 2015 ---- 10:34:24 AM

更新时间:2015年11月3日上午10:34:24

Here is a cross-browser stream.stop hack:

var MediaStream = window.MediaStream;

if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') {
    MediaStream = webkitMediaStream;
}

/*global MediaStream:true */
if (typeof MediaStream !== 'undefined' && !('stop' in MediaStream.prototype)) {
    MediaStream.prototype.stop = function() {
        this.getAudioTracks().forEach(function(track) {
            track.stop();
        });

        this.getVideoTracks().forEach(function(track) {
            track.stop();
        });
    };
}

#3


9  

Starting Webcam Video with different browsers

用不同的浏览器启动Webcam Video

For Opera 12

对于Opera 12

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

For Firefox Nightly 18.0

适用于Firefox Nightly 18.0

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

For Chrome 22

适用于Chrome 22

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

Stopping Webcam Video with different browsers

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

For Opera 12

对于Opera 12

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

For Firefox Nightly 18.0

适用于Firefox Nightly 18.0

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

For Chrome 22

适用于Chrome 22

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

With this the Webcam light go down everytime...

有了这个,网络摄像头灯每次都会消失......

#4


9  

Don't use stream.stop(), it's deprecated

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

MediaStream Deprecations

MediaStream弃用

Use stream.getTracks().forEach(track => track.stop())

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

#5


7  

You can end the stream directly using the stream object returned in the success handler to getUserMedia. e.g.

您可以使用成功处理程序中返回的流对象直接结束流到getUserMedia。例如

localMediaStream.stop()

video.src="" or null would just remove the source from video tag. It wont release the hardware.

video.src =“”或null只会从视频标记中删除源。它不会释放硬件。

#6


4  

If the .stop() is deprecated then I don't think we should re-add it like @MuazKhan dose. It's a reason as to why things get deprecated and should not be used anymore. Just create a helper function instead... Here is a more es6 version

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

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

#7


4  

Try bellow method

尝试波纹管方法

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

#8


4  

FF, Chrome and Opera has started exposing getUserMedia via navigator.mediaDevices as standard now (Might change :)

FF,Chrome和Opera已经开始通过navigator.mediaDevices作为标准公开getUserMedia(可能会改变:)

online demo

在线演示

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 audio 
localStream.getVideoTracks()[0].stop();

#9


3  

Since you need the tracks to close the streaming, and you need the stream boject to get to the tracks, the code I have used with the help of the Muaz Khan's answer above is as follows:

由于您需要轨道来关闭流媒体,并且您需要流媒体来到轨道,我在Muaz Khan的答案的帮助下使用的代码如下:

if (navigator.getUserMedia) {
    navigator.getUserMedia(constraints, function (stream) {
        videoEl.src = stream;
        videoEl.play();
        document.getElementById('close').addEventListener('click', function () {
            stopStream(stream);
        });
    }, errBack);

function stopStream(stream) {
console.log('stop called');
stream.getVideoTracks().forEach(function (track) {
    track.stop();
});

Of course this will close all the active video tracks. If you have multiple, you should select accordingly.

当然,这将关闭所有活动的视频轨道。如果您有多个,则应相应选择。

#10


0  

Using .stop() on the stream works on chrome when connected via http. It does not work when using ssl (https).

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

#11


-1  

Have a reference of stream form successHandle

有一个流形式成功的参考手柄

var streamRef;

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

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

#1


94  

EDIT

编辑

Since this answer has been originally posted the browser API has changed. .stop() is no longer available on the stream that gets passed to the callback. The developer will have to access the tracks that make up the stream (audio or video) and stop each of them individually.

由于此答案最初发布,因此浏览器API已更改。 .stop()在传递给回调的流上不再可用。开发人员必须访问组成流(音频或视频)的曲目并单独停止每个曲目。

More info here: https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active

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

Example (from the link above):

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

var track = stream.getTracks()[0];  // if only one media track
// ...
track.stop();

Browser support may differ.

浏览器支持可能不同。

Original answer

原始答案

navigator.getUserMedia provides you with a stream in the success callback, you can call .stop() on that stream to stop the recording (at least in Chrome, seems FF doesn't like it)

navigator.getUserMedia为您提供成功回调中的流,您可以在该流上调用.stop()来停止录制(至少在Chrome中,似乎FF不喜欢它)

#2


46  

You can call "stop" over MediaStream object which is going to be obsolete; new proposal is to release media tracks by calling "stop" over each media track:

你可以在MediaStream对象上调用“stop”,这个对象将会过时;新提案是通过在每个媒体轨道上调用“停止”来发布媒体曲目:

mediaStream.stop();

// or
mediaStream.getAudioTracks()[0].stop();
mediaStream.getVideoTracks()[0].stop();

Updated at Nov 03, 2015 ---- 10:34:24 AM

更新时间:2015年11月3日上午10:34:24

Here is a cross-browser stream.stop hack:

var MediaStream = window.MediaStream;

if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') {
    MediaStream = webkitMediaStream;
}

/*global MediaStream:true */
if (typeof MediaStream !== 'undefined' && !('stop' in MediaStream.prototype)) {
    MediaStream.prototype.stop = function() {
        this.getAudioTracks().forEach(function(track) {
            track.stop();
        });

        this.getVideoTracks().forEach(function(track) {
            track.stop();
        });
    };
}

#3


9  

Starting Webcam Video with different browsers

用不同的浏览器启动Webcam Video

For Opera 12

对于Opera 12

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

For Firefox Nightly 18.0

适用于Firefox Nightly 18.0

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

For Chrome 22

适用于Chrome 22

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

Stopping Webcam Video with different browsers

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

For Opera 12

对于Opera 12

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

For Firefox Nightly 18.0

适用于Firefox Nightly 18.0

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

For Chrome 22

适用于Chrome 22

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

With this the Webcam light go down everytime...

有了这个,网络摄像头灯每次都会消失......

#4


9  

Don't use stream.stop(), it's deprecated

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

MediaStream Deprecations

MediaStream弃用

Use stream.getTracks().forEach(track => track.stop())

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

#5


7  

You can end the stream directly using the stream object returned in the success handler to getUserMedia. e.g.

您可以使用成功处理程序中返回的流对象直接结束流到getUserMedia。例如

localMediaStream.stop()

video.src="" or null would just remove the source from video tag. It wont release the hardware.

video.src =“”或null只会从视频标记中删除源。它不会释放硬件。

#6


4  

If the .stop() is deprecated then I don't think we should re-add it like @MuazKhan dose. It's a reason as to why things get deprecated and should not be used anymore. Just create a helper function instead... Here is a more es6 version

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

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

#7


4  

Try bellow method

尝试波纹管方法

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

#8


4  

FF, Chrome and Opera has started exposing getUserMedia via navigator.mediaDevices as standard now (Might change :)

FF,Chrome和Opera已经开始通过navigator.mediaDevices作为标准公开getUserMedia(可能会改变:)

online demo

在线演示

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 audio 
localStream.getVideoTracks()[0].stop();

#9


3  

Since you need the tracks to close the streaming, and you need the stream boject to get to the tracks, the code I have used with the help of the Muaz Khan's answer above is as follows:

由于您需要轨道来关闭流媒体,并且您需要流媒体来到轨道,我在Muaz Khan的答案的帮助下使用的代码如下:

if (navigator.getUserMedia) {
    navigator.getUserMedia(constraints, function (stream) {
        videoEl.src = stream;
        videoEl.play();
        document.getElementById('close').addEventListener('click', function () {
            stopStream(stream);
        });
    }, errBack);

function stopStream(stream) {
console.log('stop called');
stream.getVideoTracks().forEach(function (track) {
    track.stop();
});

Of course this will close all the active video tracks. If you have multiple, you should select accordingly.

当然,这将关闭所有活动的视频轨道。如果您有多个,则应相应选择。

#10


0  

Using .stop() on the stream works on chrome when connected via http. It does not work when using ssl (https).

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

#11


-1  

Have a reference of stream form successHandle

有一个流形式成功的参考手柄

var streamRef;

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

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