伙计们,我一直在尝试使用webrtc来访问chrome的前置和后置摄像头,并且它们的工作原理十分完美,我能够在前置和后置摄像头之间进行切换。但是,默认情况下,Chrome会拿起前置摄像头,当浏览器打开时,我有什么办法让chrome接起后置摄像头?

var videoSelect = document.querySelector('select#videoSource');
var selectors = [videoSelect];

function gotDevices(deviceInfos) {
  // Handles being called several times to update labels. Preserve values.
  var values = selectors.map(function(select) {
    return select.value;
  });
  selectors.forEach(function(select) {
    while (select.firstChild) {
      select.removeChild(select.firstChild);
    }
  });
  for (var i = 0; i !== deviceInfos.length; ++i) {
    var deviceInfo = deviceInfos[i];
    var option = document.createElement('option');
    option.value = deviceInfo.deviceId;
   if (deviceInfo.kind === 'videoinput') {
      option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);
      videoSelect.appendChild(option);
    } else {
      console.log('Some other kind of source/device: ', deviceInfo);
    }
  }
  selectors.forEach(function(select, selectorIndex) {
    if (Array.prototype.slice.call(select.childNodes).some(function(n) {
      return n.value === values[selectorIndex];
    })) {
      select.value = values[selectorIndex];
    }
  });
}

navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);


我尝试按降序访问数组以先获取后置摄像头,但没有帮助

for (var  i = deviceInfos.length - 1; i >= 0; i--) {
    var deviceInfo = deviceInfos[i];
    var option = document.createElement('option');
    option.value = deviceInfo.deviceId;
           ....... //code follows


更新:我也尝试将这些行添加到上面的代码中,但是同样的响应,默认情况下打开前凸轮

for (var i = 0; i !== deviceInfos.length; ++i) {
    var deviceInfo = deviceInfos[i];


   if (deviceInfo.kind === 'videoinput' && deviceInfo.facing == "environment") {
    videoSourceId = deviceInfo.id;


    } else {
      console.log('Some other kind of source/device: ', deviceInfo);
    }
  }
//other code

var constraints = {
    video: { optional: [{sourceId: videoSourceId}] }
  };
  navigator.mediaDevices.getUserMedia(constraints).
      then(gotStream).then(gotDevices).catch(handleError);
}


PS:我尝试在其他代码中使用FaceingMode:“ environment”,但是这里有范围吗?

最佳答案

如何使用类似这样的约束:

对于后置摄像头:

{audio:false,video:{facingMode:{exact:"environment"}}}


对于FRONT相机:

{audio:false,video:{facingMode:"user"}}

关于javascript - 在Chrome 54中默认使用前置摄像头的webrtc,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40817341/

10-12 01:04