GetUserMedia - facingmode

Mikhail picture Mikhail · Aug 19, 2015 · Viewed 35.6k times · Source

I am currently using an Android tablet and GetUserMedia to take pictures in my program.

Apparently, the default camera used by GetUserMedia is the front camera. How do I use the rear camera as a default?

Here's my code for GetUserMedia:

        navigator.getUserMedia({
            "audio": false,
            "video": {
                mandatory: {
                    minWidth: this.params.dest_width,
                    minHeight: this.params.dest_height,
                    //facingMode: "environment",
                },
            }
        }, 
        function(stream) {
            // got access, attach stream to video
            video.src = window.URL.createObjectURL( stream ) || stream;
            Webcam.stream = stream;
            Webcam.loaded = true;
            Webcam.live = true;
            Webcam.dispatch('load');
            Webcam.dispatch('live');
            Webcam.flip();
        },
        function(err) {
            return self.dispatch('error', "Could not access webcam.");
        });

I inserted facingMode in the "mandatory" part but didn't work.

Please help.

Answer

jib picture jib · Sep 3, 2015

Update: facingMode is now available in Chrome for Android through the adapter.js polyfill!

facingMode is not yet implemented in Chrome for Android, but works natively in Firefox for Android.

You must use standard constraints however: (use https fiddle for Chrome):

var gum = mode => 
  navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
  .then(stream => (video.srcObject = stream))
  .catch(e => log(e));

var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());

var log = msg => div.innerHTML += msg + "<br>";
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

The { exact: } syntax means the constraint is required, and things fail if the user doesn't have the right camera. If you leave it out then the constraint is optional, which in Firefox for Android means it only changes the default in the camera chooser in the permission prompt.