Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

MediaDevices.getUserMedia()

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

El método MediaDevices.getUserMedia() indica al usuario por los permisos a usar en un dispositivo de entrada de vídeo y/o un audio tal como una cámara o  compartir pantalla y/o micrófono. Si el usuario proporciona los permisos, entonces le retornará un Promise que es resuelto por el resultado del objeto MediaStream. Si el usuario deniega el permiso, o el recurso multimedia no es válido, entonces el promise es rechazado con PermissionDeniedError o NotFoundError respectivamente. Nótese que este es posible por el retornado promise que no rechazará a ninguna, como el usuario no es requerido para tomar una elección .

Sintaxis

navigator.mediaDevices.getUserMedia(constraints)
.then(function(mediaStream) { ... })
.catch(function(error) { ... })

Retorna

Un Promise que resuelve a un objeto MediaStream.

Parámetros

constraints

Es un objeto MediaStreamConstraints espeficando los tipos de recursos a solicitar,  al lado con cualquier requerimiento para cada tipo.

Los parámetros de restricción es un objeto MediaStreamConstaints con dos miembros: video y audio, describiendo el tipo de recurso solicitado. ya sea o ambos son mas especificos .Si el navegador no puede buscar todas las pistas de recursos con los tipos especificados que reunen las restrinciones dadas, entonces el promise retornado es rechazado con NotFoundError.

La siguiente petición ambas audio y vídeo sin algun requerimiento especifico :

{ audio: true, video: true }

While information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. The following expresses a preference for 1280x720 camera resolution:

{
  audio: true,
  video: { width: 1280, height: 720 }
}

The browser will try to honor this, but may return other resolutions if an exact match is not available, or the user overrides it.

To require a capability, use the keywords min, max, or exact (a.k.a. min == max). The following demands a minimum resolution of 1280x720:

{
  audio: true,
  video: {
    width: { min: 1280 },
    height: { min: 720 }
  }
}

If no camera exists with this resolution or higher, then the returned promise will be rejected with NotFoundError, and the user will not be prompted.

The reason for the difference in behavior is that the keywords min, max, and exact are inherently mandatory, whereas plain values and a keyword called ideal are not. Here's a fuller example:

{
  audio: true,
  video: {
    width: { min: 1024, ideal: 1280, max: 1920 },
    height: { min: 776, ideal: 720, max: 1080 }
  }
}

An ideal value, when used, has gravity, which means that the browser will try to find the setting (and camera, if you have more than one), with the smallest fitness distance from the ideal values given.

Plain values are inherently ideal, which means that the first of our resolution examples above could have been written like this:

{
  audio: true,
  video: {
    width: { ideal: 1280 },
    height: { ideal: 720 }
  }
}

Not all constraints are numbers. For example, on mobile devices, the following will prefer the front camera (if one is available) over the rear one:

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

To require the rear camera, use:

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

Errors

Rejections of the returned promise are made with a MediaStreamError object that is modeled on DOMException. Relevant errors are:

SecurityError
Permission to use a media device was denied by the user or the system.
NotFoundError
No media tracks of the type specified were found that satisfy the constraints specified.

Examples

Using the Promise

This example assigns the returned MediaStream object to the appropriate element.

var p = navigator.mediaDevices.getUserMedia({ audio: true, video: true });

p.then(function(mediaStream) {
  var video = document.querySelector('video');
  video.src = window.URL.createObjectURL(mediaStream);
  video.onloadedmetadata = function(e) {
    // Do something with the video here.
  };
});

p.catch(function(err) { console.log(err.name); }); // always check for errors at the end.

Width and height

Here's an example of using mediaDevices.getUserMedia(), including a polyfill to cope with older browsers.

var promisifiedOldGUM = function(constraints, successCallback, errorCallback) {

  // First get ahold of getUserMedia, if present
  var getUserMedia = (navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia);

  // Some browsers just don't implement it - return a rejected promise with an error
  // to keep a consistent interface
  if(!getUserMedia) {
    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
  }

  // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
  return new Promise(function(successCallback, errorCallback) {
    getUserMedia.call(navigator, constraints, successCallback, errorCallback);
  });
		
}

// Older browsers might not implement mediaDevices at all, so we set an empty object first
if(navigator.mediaDevices === undefined) {
  navigator.mediaDevices = {};
}

// Some browsers partially implement mediaDevices. We can't just assign an object
// with getUserMedia as it would overwrite existing properties.
// Here, we will just add the getUserMedia property if it's missing.
if(navigator.mediaDevices.getUserMedia === undefined) {
  navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
}


// Prefer camera resolution nearest to 1280x720.
var constraints = { audio: true, video: { width: 1280, height: 720 } };

navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
  var video = document.querySelector('video');
  video.src = window.URL.createObjectURL(stream);
  video.onloadedmetadata = function(e) {
    video.play();
  };
})
.catch(function(err) {
  console.log(err.name + ": " + err.message);
});

Frame rate

Lower frame-rates may be desirable in some cases, like WebRTC transmissions with bandwidth restrictions.

var constraints = { video: { frameRate: { ideal: 10, max: 15 } } };

Front and back camera

On mobile phones.

var front = false;
document.getElementById('flip-button').onclick = function() { front = !front; };

var constraints = { video: { facingMode: (front? "user" : "environment") } };

Permissions

To use getUserMedia() in an installable app (for example, a Firefox OS app), you need to specify one or both of the following fields inside your manifest file:

"permissions": {
  "audio-capture": {
    "description": "Required to capture audio using getUserMedia()"
  },
  "video-capture": {
    "description": "Required to capture video using getUserMedia()"
  }
}

See permission: audio-capture and permission: video-capture for more information.

Specifications

Specification Status Comment
Media Capture and Streams
The definition of 'MediaDevices.getUserMedia()' in that specification.
Editor's Draft Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Stream API (Yes)[1][3]
47
36[2] No support (Yes)[1] No support
Feature Android Android Webview Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile Chrome for Android 
Stream API No support No support 36[2] No support No support No support No support

[1] Older versions of Chrome and Opera implement navigator.webkitGetUserMedia, the prefixed version of the legacy navigator.getUserMedia method.

In Chrome, this promise-based interface is only available through the adapter.js polyfill, or using the flag chrome://flags/#enable-experimental-web-platform-features.

Chrome uses an outdated constraint syntax, but the syntax described here is available through the adapter.js polyfill.

[2] Older versions of Firefox implement navigator.mozGetUserMedia, the prefixed version of the legacy navigator.getUserMedia method.

This promise-based interface and the constraint syntax described here is available as of Firefox 38. Earlier versions (32-37) used an outdated constraint syntax, but the syntax described here, as well as the promise-based interface, is available there through the adapter.js polyfill.

Opera uses an outdated constraint syntax, but the syntax described here is available through the adapter.js polyfill.

[3] Chrome throws error if the page serving the script is loaded from insecure origin (i.e. HTTP).

See also

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Cristhian, matajm
 Última actualización por: Cristhian,