Accessing a device's camera and microphone with JavaScript

- Andr茅s Cruz

En espa帽ol

Accessing a device's camera and microphone with JavaScript

This is a fascinating feature that the HTML5 API brings with it and consists of the possibility of accessing the camera and microphone (with prior user approval) of the computer or mobile device without the need to use any plugin; In this article we will learn how to access a device's camera and direct this data flow (stream) within a <video> tag; basically we are going to take a screenshot or image through the user's camera.

The HTML5 navigator.getUserMedia object

The first thing we must do is configure the JavaScript; the code that accesses the camera of the computer or device using the corresponding prefixes to maintain compatibility between the most used web browsers (Google Chrome, Mozilla Firefox and Internet Explorer):

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

Having already created the getUserMedia object in the previous step, the next thing is to initialize it with the following parameters:

  • constraints: this object takes two boolean parameters: video and audio, as you can imagine we must specify at least one of them to obtain the data stream we want to access; possible cases:
    • { video: true, audio: true }: We enable both options; therefore; the data stream will provide us with video and audio.
    • { video: true, audio: false }: We enable only the video; therefore; the data stream will provide us with only video.
    • { video: false, audio: true }: We enable only audio; therefore; the data stream will provide us with only audio.
    • { video: false, audio: false}: This option is NOT valid.
      • successCallback: This function is called if the user allows access to their camera and/or microphone and when the data stream was loaded; Therefore, this function will provide us with an object of type LocalMediaStream that contains the data stream to be manipulated and assigned to the appropriate or corresponding object, for this tutorial, it will be the <video> tag.
        errorCallback (optional): This function is the negation of the previous one; that is to say; If the user denied access or the data stream could not be loaded for some reason, this function will be executed, which provides one of the following error codes:
ErrorDescripci贸n
PERMISSION_DENIEDThe user denied permission to use the media device required for this operation.
NOT_SUPPORTED_ERRORA specified constraint is not supported by the browser.
MANDATORY_UNSATISFIED_ERRORNo media sources of the type specified in the constraints were found.
NO_DEVICES_FOUNDNo webcam found.No se encontr贸 ninguna webcam.

Firefox Developer.

Accessing a device's camera and microphone with JavaScript: Example

The complete JavaScript code of the example:

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

navigator.getUserMedia (

   // constraints
   {
      video: true,
      audio: false
   },

   // successCallback
   function(localMediaStream) {
      var video = document.querySelector(video);
      video.src = window.URL.createObjectURL(localMediaStream);
   },
   
   // errorCallback
   function(err) {
    console.log("Ocurri贸 el siguiente error: " + err);
   }

);

To summarize it, we first assign the constraints, indicating that we are only interested in the video and not the audio:

   // constraints
   {
      video: true,
      audio: false
   },

If no errors occurred, we will assign the data stream returned in the LocalMediaStream object to a video tag:

   // successCallback
   function(localMediaStream) {
      var video = document.querySelector(video);
      video.src = window.URL.createObjectURL(localMediaStream);
   },

Lastly, we handle errors (if any):

   // errorCallback
   function(err) {
    console.log("Ocurri贸 el siguiente error: " + err);
   }
  • We cannot use getUserMedia on pages that use file:// in their URLs.
  • This API requests permission from the user to access the camera and microphone.
Andr茅s Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andr茅s Cruz In Udemy

I agree to receive announcements of interest about this Blog.