Подтвердить что ты не робот

Включить заднюю камеру с помощью HTML5

Я работаю над проектом с MVC ASP.Net 4 HTML5 (браузер по умолчанию - google-chrome v29.0.1547.57). Я могу взаимодействовать с этими инструментами и фотографировать, но только с передней камерой, Как я может включить заднюю камеру? характеристика планшета: Samsung Galaxy Tab 2 Надеюсь, ты поможешь мне.

4b9b3361

Ответ 1

Отъезд https://simpl.info/getusermedia/sources/, который показывает, как вы можете выбирать источники, используя

MediaStreamTrack.getSources(gotSources);

Затем вы можете выбрать источник и передать его как необязательный в getUserMedia

var constraints = {
  audio: {
    optional: [{sourceId: audioSource}]
  },
  video: {
    optional: [{sourceId: videoSource}]
  }
};
navigator.getUserMedia(constraints, successCallback, errorCallback);

Теперь он полностью доступен в "Стабильном" Chrome и мобильном телефоне (начиная с версии v30).

Ответ 2

Демоверсию можно найти по адресу https://webrtc.github.io/samples/src/content/devices/input-output/. Это позволит получить доступ как к передней, так и к задней камере.

Многие демонстрации, которые вы найдете, используют устаревшую функцию:

MediaStreamTrack.getSources() 

Начиная с Chrome 45 и FireFox 39, вам нужно будет использовать функцию:

MediaDevices.enumerateDevices()

Пример:

if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.");
  return;
}

// List cameras and microphones.

navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    devices.forEach(function(device) {
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
    });
  })
  .catch(function(e) {
    console.log(e.name + ": " + e.message);
  });

Ответ 3

В Chrome на моем Samsung S8 я могу использовать "FaceMode" = "Среда", чтобы взять видео с "задней камеры". По умолчанию, кажется, "пользователь" ("фронтальная" камера)

в TypeScript:

    const video = document.getElementById("video");
    const constraints = {
        advanced: [{
            facingMode: "environment"
        }]
    };
    navigator.mediaDevices
        .getUserMedia({
            video: constraints
        })
        .then((stream) => {
            video.src = window.URL.createObjectURL(stream);
            video.play();
        });

ref: MediaTrackConstraints/FacingMode

Ответ 4

        //----------------------------------------------------------------------
        //  Here we list all media devices, in order to choose between
        //  the front and the back camera.
        //      videoDevices[0] : Front Camera
        //      videoDevices[1] : Back Camera
        //  I used an array to save the devices ID 
        //  which i get using devices.forEach()
        //  Then set the video resolution.
        //----------------------------------------------------------------------
        navigator.mediaDevices.enumerateDevices()
        .then(devices => {
          var videoDevices = [0,0];
          var videoDeviceIndex = 0;
          devices.forEach(function(device) {
            console.log(device.kind + ": " + device.label +
              " id = " + device.deviceId);
            if (device.kind == "videoinput") {  
              videoDevices[videoDeviceIndex++] =  device.deviceId;    
            }
          });


          var constraints =  {width: { min: 1024, ideal: 1280, max: 1920 },
          height: { min: 776, ideal: 720, max: 1080 },
          deviceId: { exact: videoDevices[1]  } 
        };
        return navigator.mediaDevices.getUserMedia({ video: constraints });

      })
        .then(stream => {
          if (window.webkitURL) {
            video.src = window.webkitURL.createObjectURL(stream);
            localMediaStream = stream;
          } else if (video.mozSrcObject !== undefined) {
            video.mozSrcObject = stream;
          } else if (video.srcObject !== undefined) {
            video.srcObject = stream;
          } else {
            video.src = stream;
          }})
        .catch(e => console.error(e));

Ответ 5

В последний раз, когда я разработал этот код, soo - это версия, которую я использую: вы вызываете непосредственно функцию whichCamera в своем коде, и вы говорите, какая камера "пользователь", "среда" или "компьютер", если вы запускаете компьютер)

`//----------------------------------------------------------------------
//  whichCamera(Type)
//    For smartphone or tablet :
//     Start the type={user,environment} camera.
//    For computer it simple :
//      type = "computer".
//----------------------------------------------------------------------
var streamSrc, cameraType;
function whichCamera(type){

  var cameraFacing;
  cameraType = type;
  if( type == "user")
    cameraFacing = 0;
  else if( type == "environment")
    cameraFacing = 1;
  else if( type == "computer"){
    cameraFacing = 2;
  }
  console.log(type+" index : "+cameraFacing);

  //  Here we list all media devices, in order to choose between
  //  the front and the rear camera.
  //      videoDevices[0] : user Camera
  //      videoDevices[1] : environment Camera
  //  Then set the video resolution.
  navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    var videoDevices, videoDeviceIndex, constraints;
    //  Initialize the array wich will contain all video resources IDs.
    //  Most of devices have two video resources (Front & Rear Camera).
    videoDevices = [0,0];
    //  Simple index to browse the videa resources array (videoDevices).
    videoDeviceIndex = 0;
    //  devices.forEach(), this function will detect all media resources (Audio, Video) of the device
    //  where we run the application.
    devices.forEach(function(device) {
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
      // If the kind of the media resource is video,
      if (device.kind == "videoinput") {
        //  then we save it on the array videoDevices.
        videoDevices[videoDeviceIndex++] =  device.deviceId;
        console.log(device.deviceId+" = "+videoDevices[videoDeviceIndex-1]);
      }
    });
    console.log("Camera facing ="+cameraFacing+" ID = "+videoDevices[videoDeviceIndex-1]);

    // Here we specified which camera we start,
    //  videoDevices[0] : Front Camera
    //  videoDevices[1] : Back Camera
    if( cameraFacing != "computer"){
      constraints = { deviceId: { exact: videoDevices[cameraFacing]  }};
      return navigator.mediaDevices.getUserMedia({ video:
                                                          constraints,
                                                          width: { min: 1280, ideal: 1600, max: 1920 },
                                                          height: { min: 720, ideal: 1200, max: 1080 }
                                                  }
                                                );
    }else
      return navigator.mediaDevices.getUserMedia({ video: true });
    })
    //  Then we retrieve the link to the video stream.
    .then(stream => {
      if (window.webkitURL) {
        video.src = window.webkitURL.createObjectURL(stream);
        localMediaStream = stream;
        console.log(localMediaStream +" = "+ stream)
      } else if (video.mozSrcObject !== undefined) {
        video.mozSrcObject = stream;
        console.log(video.mozSrcObject +" = "+ stream)
      } else if (video.srcObject !== undefined) {
        video.srcObject = stream;
        console.log(video.srcObject +" = "+ stream)
      } else {
        video.src = stream;
        console.log(video.src +" = "+ stream)
      }
      streamSrc = stream;
    })
    .catch(e => console.error(e));

}