Html 使用navigate.getUserMedia()时选择相机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16807133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:50:30  来源:igfitidea点击:

Select the camera while using navigate.getUserMedia()

javascripthtmlhtml5-videovideo-processingnavigator

提问by Vinay C

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??

我正在使用 navigate.getUserMedia() 方法在我的手机上捕获视频并对其进行进一步处理。但截至目前,它正在使用前置摄像头捕获视频。我如何使它访问后置摄像头?

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

提前致谢

采纳答案by cerkiewny

See thisfor additional information.

有关其他信息,请参阅此内容

Which camera is used is left to the device: "User agents are encouraged to default to using the user's primary or system default camera and/or microphone (as appropriate) to generate the media stream."

使用哪个摄像头由设备决定:“鼓励用户代理默认使用用户的主要或系统默认摄像头和/或麦克风(视情况而定)来生成媒体流。”

The question you may want to ask is how can you change the default camera. But as I have mentioned in the comment section this is different based on device operating system used, vendor or even model, and can be a big problem.

您可能想问的问题是如何更改默认相机。但正如我在评论部分提到的,这取决于所使用的设备操作系统、供应商甚至型号,这可能是一个大问题。

EDIT (improving accepted answer based on later one):

编辑(根据后来的答案改进接受的答案):

Please see this blog for how to change the camera source:

请参阅此博客了解如何更改相机源:

https://www.html5rocks.com/en/tutorials/getusermedia/intro/

https://www.html5rocks.com/en/tutorials/getusermedia/intro/

回答by freakTheMighty

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

simpl.info 上的这个示例演示了MediaStreamTrack.getSources从多个视频源中进行选择的用法。

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

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

I can confirm that this works in Chrome 32.

我可以确认这在 Chrome 32 中有效。

回答by user1318499

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

您可以facingMode分别为前置或后置摄像头选择“用户”或“环境”。不确定浏览器支持,但它适用于 Android Chrome 58。

Use

navigator.getUserMedia({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

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

回答by Nadhir Houari

        //----------------------------------------------------------------------
        //  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));

回答by Kurkov Igor

Long story short: If you want to select a rear camera on the OLD device which not supported facingMode constraint - you need to use sourceId: { exact: device.id }constraint inside the video: {} config.

长话短说:如果您想在不支持 facesMode 约束的 OLD 设备上选择后置摄像头 - 您需要sourceId: { exact: device.id }在视频中使用约束:{} config.

Long:

长:

export interface SourceInfo {
  facing: string; // "environment"
  id: string; // "bcb8d32aebb99fdf1d5f2fdb4ec4ec28a381b83f5e3c96cbcb30c4ab757380da"
  kind: string; // "video"
  label: string; // ""
}

code (typescript):

代码(打字稿):

(navigator as any).getUserMedia =
      (navigator as any).getUserMedia ||
      (navigator as any).webkitGetUserMedia ||
      (navigator as any).mozGetUserMedia ||
      (navigator as any).msGetUserMedia;

if (navigator.getUserMedia && (window as any).MediaStreamTrack) {
      (MediaStreamTrack as any).getSources((sources: SourceInfo[]) => {

    this.videoSources = sources.filter((source: SourceInfo) => {
      return source.kind === 'video';
      // or source.facing === 'environment'
    });
    // console.log('got video sources', this.videoSources);

    try {
      const rearCameraDevice = this.videoSources.find((device: SourceInfo) => device.facing === 'environment');
      const anyCameraDevice = this.videoSources[0];
      const constraints = {
        video: {
          mandatory: {
            sourceId: rearCameraDevice.id || anyCameraDevice.id
          }
          // these both not work with old constraints...it's new syntax
          // deviceId: this.videoSources[0].id
          // deviceId: { exact: this.videoSources[0].id }
        }
      };
      navigator.getUserMedia(
        <any>constraints, 
        this.successOldStream.bind(this), 
        this.errorOldStream.bind(this)
      );
    } catch (error) {
      console.error(error);
    }

});
} else {
  console.error('your browser not supported camera/media capturing')
}