如何使用JavaScript检查Chrome中是否正在使用网络摄像头 [英] How to check with JavaScript that webcam is being used in Chrome

查看:133
本文介绍了如何使用JavaScript检查Chrome中是否正在使用网络摄像头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果Chrome正在使用网络摄像头,则该页面的标签上会出现一个红点。如果其他页面尝试访问网络摄像头,则视频会变黑。我的问题是,是否可以使用JavaScript检查是否正在使用网络摄像头?如何?

If webcam is being used in Chrome, there will be a red dot on the tab for that page. And if other pages try to access webcam will get black for video. My question is, is it able to check with JavaScript that webcam is being used? How?

通过使用navigator.getUserMedia,我尝试了以下代码:

By using navigator.getUserMedia, I tried following code:

navigator.getUserMedia = navigator.getUserMedia ||
    navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
    navigator.msGetUserMedia;

navigator.getUserMedia({ audio: true, video: true }, function (stream) {
    var mediaStreamTrack = stream.getVideoTracks()[0];
    if (typeof mediaStreamTrack != "undefined") {
        mediaStreamTrack.onended = function () {alert('Your webcam is busy!')}
    } else errorMessage('Permission denied!');
}, function (e) {alert("Error: " + e.name);});

当页面流式传输视频时,将代码粘贴到控制台中,我没有回复。

Pasting the code into console when a page is streaming video, I got no response.

任何想法?谢谢!

推荐答案

请尝试使用启用 readyState MediaStreamTrack的属性 对象。然后,您可以使用JavaScript数组函数(例如 some()来遍历轨道并检查是否有已启用设置为true和&& readyState 等于字符串'live':

Try instead using the enabled and readyState properties of the MediaStreamTrack object. You can then use a JavaScript array function such as some() to iterate through the tracks and check if any have enabled set to true and && readyState equal to string 'live":

navigator.getUserMedia = (navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetUserMedia ||
  navigator.msGetUserMedia);

if (navigator.getUserMedia) {
  navigator.getUserMedia({
      audio: true,
      video: true
    },
    function(stream) {
      // returns true if any tracks have active state of true
      var result = stream.getVideoTracks().some(function(track) {
        return track.enabled && track.readyState === 'live';
      });

      if (result) {
        alert('Your webcam is busy!');
      } else {
        alert('Not busy');
      }
    },
    function(e) {
      alert("Error: " + e.name);
    });
}

希望有帮助!

这篇关于如何使用JavaScript检查Chrome中是否正在使用网络摄像头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆