仅使用JavaScript如何检查用户是否有网络摄像头?

29

使用JavaScript,仅凭代码是否能知道用户是否有网络摄像头吗?我不想使用任何插件来实现。


http://stackoverflow.com/questions/20641213/how-can-i-check-if-user-has-a-webcam-or-not - Dhaval Marthak
@DhavalMarthak,亲爱的,我不想使用任何插件。我只想使用JavaScript进行检查。 - Jimit
1
@DhavalMarthak 不是这样的。 :) 请查看我的答案。 - Scimonster
2
@DhavalMarthak HTML5 意味着对 JS 的补充。请注意,我不使用任何 HTML 代码,只用 JS。 - Scimonster
@gtournie的回答应该被接受。 - Colin 't Hart
8个回答

42

你不一定需要获得权限才能知道用户是否有摄像头,你可以使用 enumerateDevices 进行检查:

function detectWebcam(callback) {
  let md = navigator.mediaDevices;
  if (!md || !md.enumerateDevices) return callback(false);
  md.enumerateDevices().then(devices => {
    callback(devices.some(device => 'videoinput' === device.kind));
  })
}

detectWebcam(function(hasWebcam) {
  console.log('Webcam: ' + (hasWebcam ? 'yes' : 'no'));
})

你能提供不使用回调的解决方案吗? - Avatar
@Avatar 我不明白你的意思。回调函数会提供给你信息,如果你不使用它,就无法知道用户是否有摄像头... - gtournie
@Avatar 我不明白你的意思。回调函数会提供给你信息,如果你不使用它,你就无法知道用户是否有摄像头... - undefined

32
您可以使用新的HTML5 API来检查他们是否允许您使用网络摄像头。毕竟,从代码的角度来看,如果他们拒绝权限,他们可能就没有网络摄像头了。
请参见navigator.getUserMedia()
编辑:
navigator.getMedia = ( navigator.getUserMedia || // use the proper vendor prefix
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

navigator.getMedia({video: true}, function() {
  // webcam is available
}, function() {
  // webcam is not available
});

2
getUserMedia()在不安全的源上已经无法使用。为了使用此功能,您应该考虑将应用程序切换到安全源,例如HTTPS。有关更多详细信息,请参见https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins。 - Stepan Suvorov

4

您可以使用此插件来检查用户是否有网络摄像头:http://www.xarg.org/project/jquery-webcam-plugin/

if(webcam.getCameraList().length == 0){  
   alert('You don\'t have a web camera');  
}

从这里获取: 如何检查用户是否有网络摄像头? 编辑: 我看到你更新了你的问题,说你不想使用插件。在这种情况下,你可以尝试使用getUserMedia API:
function success(stream){
  // The success function receives an argument which points to the webcam stream
  document.getElementById('myVideo').src = stream; 
}

function error(){
  alert("No webcam for you, matey!");
}

if (navigator.getUserMedia) { 
   navigator.getUserMedia({video:true, audio:false}, success, error);
} else { 
   error();
}

来源: http://www.iandevlin.com/blog/2012/06/html5/filtering-a-webcam-using-getusermedia-and-html5-canvas

本文介绍了如何使用getUserMedia和HTML5 Canvas来过滤Webcam视频流的方法。该方法利用Canvas API提供的像素级别的访问,可以对视频帧进行实时处理。此外,它还演示了如何创建自己的过滤器函数,并将其应用到视频流中。


1

你无法读取当前浏览器设置。 我们唯一能做的就是尝试访问网络摄像头/麦克风,看看是否能够访问该设备,如...

navigator.getMedia({video: true}, function() {
  // webcam is available
}, function() {
  // webcam is not available
});

但是 **** 请注意,如果您遵循这种方法,请注意....

另外请注意,您必须使用HTTPS才能使用网络摄像头/麦克风,并且它将提示您浏览器特定的权限弹出窗口,其中只有允许和阻止按钮仅一次,您将不会再次看到此权限弹出窗口,因为HTTPS保存了该权限。

唯一重新获取此权限弹出窗口的方法是:

  1. 清除缓存并
  2. 重置浏览器设置
  3. 打开浏览器的新实例。

FYI ... 您无法使用JavaScript操纵浏览器特定设置 因此,除非你有时间浪费,否则不要走那条路。


根本不是这样的。请参考@gtournie的答案,了解如何实现。 - Colin 't Hart
实际上,Navigator.getUserMedia()已经被弃用,建议使用MediaDevices.getUserMedia()。 - Hypothesis

1

Navigator.getUserMedia()已于2019年被弃用。要访问网络摄像头,请改用MediaDevices.getUserMedia()

请注意,如果当前文档未安全加载,则navigator.mediaDevices将返回undefined。从localhost提供的URL通常是可以的。

用于测试和访问网络摄像头的示例代码:

const constraints = {
    audio: false,
    video: { width: 1280, height: 720 },
};
if (!navigator.mediaDevices) {
    console.log("Document not secure. Unable to capture WebCam.");
} else {
    navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function(stream) {
            //show webcam stream
            let videoIn = document.createElement("video");
            videoIn.autoplay = true;
            document.body.appendChild(videoIn);
            videoIn.srcObject = stream;
        })
        .catch(function(err) {
            console.log("Unable to capture WebCam.", err);
        });
}

0
async function detectWebcam() {
    try {

        var md = navigator.mediaDevices;
        var results = false;

        if (!md || !md.enumerateDevices) results = false;

        const devices = await md.enumerateDevices();
        results = devices.some(device => 'videoinput' === device.kind);

        return results;

    } catch (error) { return false; }
}

请阅读此帮助页面,了解如何正确格式化代码。链接 - costaparas

0

在这里,受其他答案的启发,作为我正在开发的实现的一部分,我正在使用下面的函数返回一个布尔值,以检查是否有活动的流。

该项目有点老旧,因此使用了jQuery和ES5,但希望对某人有用:

function() {
  var deferred = $.Deferred();

  navigator.mediaDevices.getUserMedia(VIDEO_CONSTRAINTS)
    .then(function(stream) { deferred.resolve(stream.active); })
    .catch(function() { deferred.resolve(false) })

  return deferred.promise()
}

然后可以按如下方式使用:

checkStreamActive()
  .then(function(activeStream) {
    if(activeStream) {
      // do something
    } else {
    // do something else
  }
}) 

-1

强调文本尝试使用JavaScript警告框来检查设备是否具有网络摄像头查看此图像

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        $(document).ready(function () {
            webcam_check_func();
        });

        function webcam_check_func() {
            var hasWebcam = false;
            var device = [];
            if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
                
                navigator.enumerateDevices = function (callback) {
                    navigator.mediaDevices.enumerateDevices().then(callback);
                };
                navigator.enumerateDevices(function (devices) {
                    devices.forEach(function (my_device) {

                        if (my_device.kind === 'videoinput') {
                            debugger;
                            hasWebcam = true;
                        }
                    }
                    );
                    alert("Has Web Camera -->" + hasWebcam);
                });
            }

        }

    </script>

</head>
<body>
</body>
</html>


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接