0

So I've been tasked with creating a demo using HTML 5 Video element to get a picture of the user and then doing some processing server-side. testing on a Surface Pro 4 seems to ignore the facingMode: 'user' options from navigator.mediaDevices.getUserMedia function.

    navigator.mediaDevices.getUserMedia({ audio: false, video: { facingMode: "user" } })
    .then(handleSuccess, stopCameras);

    var handleSuccess = (stream) => {
        customer.srcObject = stream;
        videotracks = stream.getVideoTracks();
    }

The handleSuccess calls getVideoTracks on the stream, but only the rear-facing camera is in the array.

How do I ensure that this will only target the user-facing camera?

robjam
  • 969
  • 1
  • 11
  • 24

1 Answers1

0

You need first to enumerate the number of cameras and save them in a var like this:

var camcounter; // camera counter
var camera_id = {}; // array of cameras by device id

navigator.mediaDevices.enumerateDevices()
.then(function(myStream) {
    myStream.forEach(function(myStream) {
        if(myStream.kind === 'videoinput') {
            camcounter++; //camera count
            camera_id.push(myStream.deviceId); //pushing the device ID to the array
            console.log(myStream.kind + ": " + myStream.label + " id = " + myStream.deviceId);                        
        }
    });
})
.then(function(myStream) { 
    if(camcounter === 1) { //building mediaContraints if just one camera found
        console.log('one camera profile');
        mediaConstraints = {
            video: {deviceId: {exact: camera_id[0]}},
            audio: {mandatory: {echoCancellation: true, googAutoGainControl: true, googNoiseSuppression: true, googHighpassFilter: true, googTypingNoiseDetection: true}}
        };
    }
    else {
        if(camcounter === 2) { //building mediaContraints if two cameras found
            mediaConstraints = {
                video: {deviceId: {exact: camera_id[1]}},
                audio: {mandatory: {echoCancellation: true, googAutoGainControl: true, googNoiseSuppression: true, googHighpassFilter: true, googTypingNoiseDetection: true}}
            };
        }
        else {
            console.log('no camera or more than 2 cameras');
        }
    }
})
.then(function(myStream) {
    navigator.mediaDevices.getUserMedia(mediaConstraints)
        .then(function(myStream) {
            stream = myStream;
            usercam1.srcObject = stream;       
            pc = new PeerConnection(servers);      
            pc.addStream(stream);
            pc.ontrack = function(e) {
            usercam2.srcObject = e.streams[0]; 
        };
        pc.onicecandidate = function(event) {
            if(event.candidate) {
                send({type: 'candidate', candidate: event.candidate});   
            }
        }; 
    })
})
.catch(function(error) {
    console.log('error switching camera :' + error + ' camecounter is: ' + camcounter);
 });