简体   繁体   English

如何使用 JavaScript 检查 Chrome 中正在使用网络摄像头

[英]How to check with JavaScript that webcam is being used in Chrome

If webcam is being used in Chrome, there will be a red dot on the tab for that page.如果在 Chrome 中使用网络摄像头,则该页面的选项卡上会出现一个红点。 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?我的问题是,它是否能够使用 JavaScript 检查正在使用网络摄像头? How?如何?

By using navigator.getUserMedia, I tried following code:通过使用 navigator.getUserMedia,我尝试了以下代码:

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.当页面正在流式传输视频时将代码粘贴到控制台中,我没有收到任何响应。

Any ideas?有任何想法吗? Thanks!谢谢!

Try instead using the enabled and readyState properties of the MediaStreamTrack object .尝试使用MediaStreamTrack 对象enabledreadyState属性。 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":然后,您可以使用诸如some()类的 JavaScript 数组函数来遍历轨道并检查是否有任何enabled设置为 true 并且 && readyState等于字符串“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);
    });
}

Hopefully that helps!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM