【问题标题】:Access webcam without Flash无需 Flash 即可访问网络摄像头
【发布时间】:2012-03-27 12:38:49
【问题描述】:

我想使用 HTML 5 元素和 JavaScript 创建一个视频聊天应用程序,我不想使用 Flash 访问用户的网络摄像头。

我怎样才能只使用 HTML 和 JavaScript 来完成这项工作?

【问题讨论】:

标签: javascript html webcam


【解决方案1】:

在撰写本文时,最好的解决方案是 WebRTC。它是supported in Chrome, Mozilla and Opera,但在 Internet Explorer 和 Safari 中仍然不可用。

简约演示。

Index.html

<!DOCTYPE html>
<head>
</head>
<body>
    <video></video>
    <script src="webcam.js"></script>
</body>

webcam.js

(function () {
    navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia);

    navigator.getMedia(
        // constraints
        {video:true, audio:false},

        // success callback
        function (mediaStream) {
            var video = document.getElementsByTagName('video')[0];
            video.src = window.URL.createObjectURL(mediaStream);
            video.play();
        },   
        //handle error
        function (error) {
            console.log(error);
        })   
})();

阅读更多herethere

【讨论】:

  • 在用户单击 DOM 中的某些内容之前,此特定代码将无法在 Chrome 上运行。我添加了一个调用上述函数的按钮,一切正常。
  • @taystack 你有小提琴什么的吗?我很好奇怎么做。
  • @shifu developers.google.com/web/updates/2017/09/… 会告诉你所有的事情。
【解决方案2】:

尽管提供的示例很棒并且启发了我,但在撰写此答案时,Navigator.getUserMedia() 函数已过时。我已经使用video 标签的srcObejct 和promise 方法重写了提供的示例。

<!DOCTYPE html>
<head>
</head>
<body>
    <video id="video-cam"></video>
    <script>
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(mediaStream => {
            const video = document.getElementById('video-cam');
            video.srcObject = mediaStream;
            video.onloadedmetadata = (e) => {
                video.play();
            };
        })
        .catch(error => {
            alert('You have to enable the mike and the camera');
        });
    </script>
</body>

【讨论】:

  • 只是一个普通的css样式#video-cam { height: 100px;宽度:100px; }
猜你喜欢
  • 2013-11-26
  • 1970-01-01
  • 2011-03-07
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多