9

I can get mediaDevices of 'videoinput' kind via navigator.mediaDevices.enumerateDevices() promise.

I can get mediaStream via navigator.mediaDevices.getUserMedia(constraints) promise.

What should constraints look like in order to have two video tracks in userMedia?

vadirn
  • 1,715
  • 4
  • 15
  • 16
  • What do you mean "in userMedia"? Are you trying to get two cameras at once, or are you trying to limit the possible choices down to two cameras (including what's shown in the permission prompt that some browsers implement) when `getUserMedia` is called? – jib Nov 18 '15 at 01:55

1 Answers1

23

You can get max one video track and one audio track each time you call getUserMedia(), but you can call it multiple times. This may ask the user more than once though, depending on https, browser, and what the user does.

Following the standard (which at this time requires using adapter.js in Chrome), to get a specific "videoinput" device, pass its deviceId into getUserMedia using the deviceId constraint:

navigator.mediaDevices.enumerateDevices()
.then(devices => {
  var camera = devices.find(device => device.kind == "videoinput");
  if (camera) {
    var constraints = { deviceId: { exact: camera.deviceId } };
    return navigator.mediaDevices.getUserMedia({ video: constraints });
  }
})
.then(stream => video.srcObject = stream)
.catch(e => console.error(e));

The exact keyword makes the constraint required, guaranteeing it'll return only the right one, or fail.

If you want two cameras, you'll have to call getUserMedia again with a different deviceId, and hope the OS you're on supports it (e.g. phones generally don't).

jib
  • 40,579
  • 17
  • 100
  • 158
  • Thank you! But we still can switch from back to front camera on phones, right? – vadirn Nov 18 '15 at 09:16
  • 3
    Yes, provided you `.stop()` existing tracks before calling `getUserMedia` again. You can use either `enumerateDevices` or the `facingMode` constraint for this http://stackoverflow.com/a/32364912/918910 – jib Nov 18 '15 at 18:57