【问题标题】:How to use smartphone camera when access localhost website?访问 localhost 网站时如何使用智能手机摄像头?
【发布时间】:2020-11-18 01:48:21
【问题描述】:

我想在我的网站上制作 QR 阅读器功能。我有几个可以做到这一点的 javascript 插件。我已经在我的计算机上的 localhost 上运行了脚本,运行良好。然后我尝试通过访问我的笔记本电脑 IP 地址 (how I do it) 在我的智能手机中运行脚本。该页面在智能手机中加载良好,但无法检测到摄像头。这里是我尝试过的 QR 扫描仪插件:

【问题讨论】:

  • 这是安全设置问题。解决方案在这里:stackoverflow

标签: javascript jquery localhost html5-video smartphone


【解决方案1】:

我已经编写条形码扫描器 javascript 文件一年多了,所以我遇到了这个问题。你有没有试过在你的 JS 中添加这样的东西?这将检测您的媒体设备。我附上了一个通用的获取用户媒体脚本,它与我使用的非常相似。您可能需要根据您为元素命名的内容更改一些脚本措辞,但这应该会为您提供所需的内容。

// Older browsers might not implement mediaDevices at all, so we set an empty object first
if (navigator.mediaDevices === undefined) {
  navigator.mediaDevices = {};
}

// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if (navigator.mediaDevices.getUserMedia === undefined) {
  navigator.mediaDevices.getUserMedia = function(constraints) {

    // First get ahold of the legacy getUserMedia, if present
    var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

    // Some browsers just don't implement it - return a rejected promise with an error
    // to keep a consistent interface
    if (!getUserMedia) {
      return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
    }

    // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
    return new Promise(function(resolve, reject) {
      getUserMedia.call(navigator, constraints, resolve, reject);
    });
  }
}

navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(function(stream) {
  var video = document.querySelector('video');
  // Older browsers may not have srcObject
  if ("srcObject" in video) {
    video.srcObject = stream;
  } else {
    // Avoid using this in new browsers, as it is going away.
    video.src = window.URL.createObjectURL(stream);
  }
  video.onloadedmetadata = function(e) {
    video.play();
  };
})
.catch(function(err) {
  console.log(err.name + ": " + err.message);
}); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多