Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

html - 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. 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?

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.

Any ideas? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Hopefully that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...