重新连接网络摄像头时,WebRTC 继续视频流

WebRTC continue video stream when webcam is reconnected

我通过 getUserMedia 获得了简单的视频流,但我想处理当我正在流式传输的网络摄像头断开连接或不可用时的情况。所以我在传递给 successCallback 函数的 stream 对象上找到了 oninactive 事件。另外,我想在插入完全相同的 webcam/mediaDevice 时重新启动视频流。

代码示例:

navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

navigator.getUserMedia(constrains, function successCallback(stream) {
        this.video.src = URL.createObjectURL(stream);
        stream.oninactive = function (error) {
            //this handler runs when device becomes unavailable.
            this.onStreamInactive(error, stream);
        }.bind(this);
    }.bind(this), function errorCallback () {});

基于上面的例子,我可以:

  1. 检测最近连接的媒体设备
  2. 检查它是否与我流式传输的设备相同

回答有点晚,但看起来您可以使用 MediaDevices.ondevicechange to attach an event handler, and then in the event handler you can query MediaDevices.enumerateDevices() 来获取完整列表。然后您检查设备列表,通过比较您拥有的缓存列表并将属性与您保存的当前设备属性的记录进行比较来识别最近添加的设备。这些链接有更详尽的示例。

改编自 ondevicechange 参考页

navigator.mediaDevices.ondevicechange = function(event) {
  navigator.mediaDevices.enumerateDevices()
    .then(function(devices) {
      devices.forEach(function(device) {
        console.log(device);
        // check if this is the device that was disconnected
      });
    });
}

请注意 enumerateDevices 返回的 device 对象的类型描述为 here

浏览器支持 在撰写本文时,它看起来很不完整。请参阅此相关问题:Audio devices plugin and plugout event on chrome browser 以进行进一步讨论,但简短的故事是针对 Chrome 您需要启用 "Experimental Web Platform features" 标志。

更好的方法是使用 MediaDevices.ondevicechange(),如该线程中其他答案中所述,但它仍然落后于 Chrome 上的标志。不要使用 ondevicechange() 来枚举设备,而是在开始呼叫时定期轮询 MediaDevices.enumerateDevices(),在每个轮询间隔结束时比较您从上一次轮询中的设备获得的设备列表。这样您就可以在通话过程中知道新设备added/remove。