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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11642926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:38:24  来源:igfitidea点击:

Stop/Close webcam which is opened by navigator.getUserMedia

javascripthtmlhtml5-videowebrtcgetusermedia

提问by Shih-En Chou

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 代码可以停止或关闭网络摄像头?谢谢大家。

回答by andrei

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):

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

stream.getTracks().forEach(function(track) {
  track.stop();
});

Browser support may differ.

浏览器支持可能不同。

Original answer

原答案

navigator.getUserMediaprovides 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 不喜欢它)

回答by Muaz Khan

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

您可以在即将过时的MediaStream对象上调用“停止” ;新提议是通过在每个媒体轨道上调用“停止”来发布媒体轨道:

mediaStream.stop();

// or
mediaStream.getTracks()[0].stop();
mediaStream.getTracks()[1].stop();


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

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

Here is a cross-browser stream.stophack:

这是一个跨浏览器的stream.stop黑客攻击:

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.getTracks().forEach(function(track) {
            track.stop();
        });
    };
}

回答by sol404

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

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

MediaStream Deprecations

媒体流弃用

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

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

回答by Alain Saurat

Starting Webcam Video with different browsers

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

For Opera 12

歌剧 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

铬 22

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

Stopping Webcam Video with different browsers

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

For Opera 12

歌剧 12

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

For Firefox Nightly 18.0

对于 Firefox Nightly 18.0

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

For Chrome 22

铬 22

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

With this the Webcam light go down everytime...

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

回答by Sasi Varunan

FF, Chrome and Opera has started exposing getUserMediavia navigator.mediaDevicesas standard now (Might change :)

FF,Chrome和Opera已经开始暴露getUserMedia通过navigator.mediaDevices标准现在(可能会更改:)

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

回答by Bhavin

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 nullwould just remove the source from video tag. It wont release the hardware.

video.src=""或者null只是从视频标签中删除源。它不会释放硬件。

回答by Veshraj Joshi

Suppose we have streaming in video tag and id is video - <video id="video"></video>then we should have following code -

假设我们在视频标签中有流媒体并且 id 是视频 -<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;

回答by imal hasaranga perera

Try method below:

试试下面的方法:

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

回答by Endless

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

回答by mcy

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

由于您需要曲目来关闭流媒体,并且您需要streamboject 才能进入曲目,因此我在上面 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.

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