Skip to content Skip to sidebar Skip to footer

How To Select Proper Backfacing Camera In Javascript?

I am using navigator.mediaDevices.getUserMedia to open MediaStream from camera device within a web browser. My app wants to do some realtime image processing in WebAssembly and for

Solution 1:

I placed all the cameras by id into array like that

      navigator.mediaDevices.enumerateDevices()
        .then(function(devices) {
        
        for(;devices[i];){
        if(devices[i].kind == "videoinput"){
            that.aCameras.push(   [devices[i].deviceId , devices[i].label]   )
            j++;            
            }
        i++;
        }
    });

Than on the event that flip the camera by pressing the button i did this:

var defaultsOpts = { audio: false, video: true };
      defaultsOpts.video = { 
              deviceId: that.aCameras[that.currentCamera][0]
      };
      if ( that.aCameras.length-1 != that.currentCamera ){
          that.currentCamera++;
      }
      else{
          that.currentCamera = 0;
      }      
      navigator.mediaDevices.getUserMedia(defaultsOpts)
            .then(function (stream) {
                  vid.srcObject = stream;
                  localstream = stream;
                  vid.play();
               });
          
       });

like that instead of using user/enviroment, my problem was sort of solved.

hope will help you too.

Regards, Avi.

Solution 2:

as this problem is somehow still relevant today, currently the best way of detecting "non-telephoto" / "non-wide-lens" camera is IMHO simply to check torch parameter.

(As this is the literally only parameter, which on some devices different “standard” camera and the others.)

I am doing this:

  • open default camera stream( = facingMode: { ideal: 'environment' },, find out, if torch is present
  • if not, close this camera stream and iterate for each device; try to detect torch
  • if nothing is found, fall back to the first camera; or possibly get better by some combination of other parameters - eg. focusDistance.
  • (save selected camera id to eg. cookie, so next time is for this user quicker)

Post a Comment for "How To Select Proper Backfacing Camera In Javascript?"