Nodarii
Nodarii

Reputation: 984

WebRTC continue video stream when webcam is reconnected

I've got simple video stream working via getUserMedia, but I would like to handle case when webCam what i'm streaming from becomes disconnected or unavailable. So I've found oninactive event on stream object passed to successCallback function. Also I would like to restart video stream when exactly same webcam/mediaDevice will be plugged in.

Code example:

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 () {});

Based on the example above how i can:

  1. Detect recently connected media device
  2. Check is it the same device what I was streaming from

Upvotes: 4

Views: 2151

Answers (2)

prerak
prerak

Reputation: 176

A better way would be to use MediaDevices.ondevicechange() as mentioned in the other answer in this thread, but it is still behind a flag on Chrome. Instead of using ondevicechange() to enumerate devices, poll MediaDevices.enumerateDevices() at regular interval when you start the call, at end of every poll interval compare the list of devices you get from the devices in the previous poll. This way you can know the new devices added/remove during the call.

Upvotes: 1

alexanderbird
alexanderbird

Reputation: 4198

A little late to answer, but it looks like you can use MediaDevices.ondevicechange to attach an event handler, and then in the event handler you can query MediaDevices.enumerateDevices() to get the full list. Then you inspect the list of devices, identify the one that was recently added by comparing by a cached list you have, and comparing properties to a record you kept of the properties of the current device. The links have more thorough examples.

Adapted from the ondevicechange reference page

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
      });
    });
}

Note that the type of the device objects returned by enumerateDevices is described here

Browser Support It looks like it's pretty patchy as of writing this. See this related question: Audio devices plugin and plugout event on chrome browser for further discussion, but the short story is for Chrome you'll need to enable the "Experimental Web Platform features" flag.

Upvotes: 0

Related Questions