Which Camera will open getUserMedia API in mobile Device? Front or Rear?

后端 未结 3 722
[愿得一人]
[愿得一人] 2021-02-02 17:26

While using getUserMedia API to access camera in desktop it will open web camera.of course it is help to video communication.but which camera is invoked when it is used in mobil

3条回答
  •  无人及你
    2021-02-02 17:50

    There's a solution where the user can select one of the cameras.

    Enable rear camera with HTML5

    By evaluating sourceInfo.facing from the following code, you can select a camera ('user' or 'environment') (which works on current chrome >= 30): https://simpl.info/getusermedia/sources/

    'use strict';
    
    var videoElement = document.querySelector('video');
    var audioSelect = document.querySelector('select#audioSource');
    var videoSelect = document.querySelector('select#videoSource');
    
    navigator.getUserMedia = navigator.getUserMedia ||
      navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
    
    function gotSources(sourceInfos) {
      for (var i = 0; i !== sourceInfos.length; ++i) {
        var sourceInfo = sourceInfos[i];
        var option = document.createElement('option');
        option.value = sourceInfo.id;
        if (sourceInfo.kind === 'audio') {
          option.text = sourceInfo.label || 'microphone ' + (audioSelect.length + 1);
          audioSelect.appendChild(option);
        } else if (sourceInfo.kind === 'video') {
          option.text = sourceInfo.label || 'camera ' + (videoSelect.length + 1);
          videoSelect.appendChild(option);
        } else {
          console.log('Some other kind of source: ', sourceInfo);
        }
      }
    }
    
    if (typeof MediaStreamTrack === 'undefined'){
      alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
    } else {
      MediaStreamTrack.getSources(gotSources);
    }
    
    
    function successCallback(stream) {
      window.stream = stream; // make stream available to console
      videoElement.src = window.URL.createObjectURL(stream);
      videoElement.play();
    }
    
    function errorCallback(error){
      console.log('navigator.getUserMedia error: ', error);
    }
    
    function start(){
      if (!!window.stream) {
        videoElement.src = null;
        window.stream.stop();
      }
      var audioSource = audioSelect.value;
      var videoSource = videoSelect.value;
      var constraints = {
        audio: {
          optional: [{sourceId: audioSource}]
        },
        video: {
          optional: [{sourceId: videoSource}]
        }
      };
      navigator.getUserMedia(constraints, successCallback, errorCallback);
    }
    
    audioSelect.onchange = start;
    videoSelect.onchange = start;
    
    start();
    

提交回复
热议问题