如何在 Chrome 中使用 getUserMedia 对象播放视频

How to get play video with getUserMedia object in Chrome

我正在使用 webrtc 开发 Web 应用程序,作为第一个教程,我只是尝试通过 getUserMedia 访问我的摄像头和麦克风。

这是我的代码:

index.html:

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
    <nav class="navbar navbar-fixed-top navbar-dark bg-inverse">
        <a href="#" class="navbar-brand">Demo WebRTC</a>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col-sm-6">
                <h2>Réccéption</h2>
                <video id="receiver-video" width="100%" height="400px" src=""></video>
            </div>

            <div class="col-sm-6">
                <h2>Envoi</h2>
                <video id="emitter-video" width="100%" height="400px" src=""></video>
                <p><button id="start">Démarrer la conversation</button></p>
            </div>
        </div>

    </div>


    <script src="app.js" charset="utf-8"></script>


    </body>


</html>

app.js

document.querySelector('#start').addEventListener('click', function function_name(e) {

    navigator.getUserMedia = ( navigator.getUserMedia ||
                       navigator.webkitGetUserMedia ||
                       navigator.mozGetUserMedia ||
                       navigator.msGetUserMedia);

    navigator.getUserMedia({
        video: true,
        audio: true
    }, function(stream){

        let emitterVideo = document.querySelector('#emitter-video')
        emitterVideo.src = window.URL.createObjectURL(stream)
        emitterVideo.play()
    }, function() {})
})

使用此代码,我可以访问摄像头和麦克风并在 FireFox 中播放视频,但是当我在 Chrome 中打开它时,我无法播放视频并出现以下错误在控制台中被抛出:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.
Promise (async)
(anonymous) @ app.js:15 

我正在使用 Chrome 版本 60.0.3112.90。

我想您使用的教程不是最新的。不鼓励使用 window.URL.createObjectURL

意思代替

emitterVideo.src = window.URL.createObjectURL(stream)

你应该使用 srcObject 赋值

emitterVideo.srcObject = stream

如果您想坚持使用本教程,还有另一种选择。我假设您只是在浏览器中打开 index.html。例如,如果您改为通过 python -m SimpleHTTPServer 8000 提供服务,它也可以。

编辑:一些 createObjectURL

URL.createObjectURL(stream) is a hack. Stop using it. Efforts are underway to remove it.

Use video.srcObject = stream directly instead. It is standard and well-implemented.

This assignment of a local resource should never have been a URL in the first place and is a red herring to understanding how WebRTC works.