Search code examples
javascripthtmlhtml5-videovideo-processingnavigator

Select the camera while using navigate.getUserMedia()


I am using navigate.getUserMedia() method to capture video on my mobile and do further processing on it. But as of now it is capturing the video using the front camera. How do i make it to access the rear facing camera??

Below is some sample code which i am using in my application:

  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
  if (navigator.getUserMedia){
    navigator.getUserMedia({video: true}, successCallback, errorCallback);

Thanks in advance


Solution

  • You can use facingMode to choose "user" or "environment" for front or back camera respectively. Not sure about browser support but it works on Android Chrome 58.

    Use

    navigator.getU

    serMedia({video: { facingMode: { exact: "environment" } } },
    successCallback, errorCallback);
    

    or, to allow fallback to some other camera

    navigator.getUserMedia({video: { facingMode: "environment" } },
    successCallback, errorCallback);
    instead of
    
    navigator.getUserMedia({video: true}, successCallback, errorCallback);
    

    From https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

    This example on simpl.info demonstrates the use of MediaStreamTrack.getSources to select from multiple video sources.

    https://simpl.info/getusermedia/sources/

    I can confirm that this works in Chrome 32.