How should I format (Android) / Chrome getUserMedia () restrictions?

I tried to access the rear camera on the LG G4 Android phone with Chrome. I can filter the video sources from MediaStreamTrack.getSources(), but when I try to set a restriction to prefer the rear camera, I get an error message TypeError: Failed to execute 'webkitGetUserMedia' on 'Navigator': Malformed constraints object.Below I have the code that I use to filter the video sources

if (navigator.getUserMedia) {
  if (MediaStreamTrack.getSources) {
    MediaStreamTrack.getSources(function(sourceInfos) {
      var sources = [];
      _.forEach(sourceInfos, function(info) {
        if (info.kind === 'video') {
          sources.push(info);
        }              
      })
      handleSources(sources);
    })
  }
}

Then I try to select the source in the function handleSourcesmentioned above:

function handleSources(sources) {
  var constraints = {
    video: {
      facingMode: 'environment' // Yeah, this definitely doesn't work.
    }
  }
  getMedia(constraints); // This calls getUserMedia with the selected contraints
}

, , , . , , , . Googling https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Parameters, .

+4
2

, / Android API . , , ( ), , . , , API ( , , , ).

API, , - , ( API ) , a WebRTC 2013 . , . getMedia :

var constraints = {
  video: {
    mandatory: {
      facingMode: 'environment'
    }
  }
}
getMedia(constraints);

, , ( ):

var constraints = {
  video: {
    optional: [{
      facingMode: 'environment'
    }]
  }
}
getMedia(constraints);

, , , , . , facingMode Android 5.0 ( , , ); ( , ):

var constraints = {
  video: {
    mandatory: {
      sourceId: '<your source ID here>'
    }
  }
}
getMedia(constraints);

Android 5.0, , MediaStreamTrack.getSources() , ( facing ). , "" navigator.mediaDevices.enumerateDevices() .

, , API . ( , ), BrowserStack ( ), console.log() Vorlon.js ( console.log() , , ).

- - API-, , .

+4

Browser Compatibility MDN, , :

Chrome , adapter.js polyfill.

, .js facingMode Chrome Android ( https 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().map(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.imtqy.com/adapter/adapter-latest.js"></script>
Hide result

{ exact: } , , , . , ( Firefox Android ).

adapter.js navigator.mediaDevices.enumerateDevices(), MediaStreamTrack.getSources.

+3

Source: https://habr.com/ru/post/1623575/


All Articles