Joris
Joris

Reputation: 33

Navigator.getUserMedia() deprecated. How to change to MediaDevices.getUserMedia()

Hey im trying to build a face-ai in browser. Everything works fine on my laptop but when I try to run it on a raspberry Pi it says navigator.getUserMedia() is deprecated. I know there is a new method called MediaDevices.getUserMedia but I don't have any idea how to implement it.

Code

const video = document.getElementById('video')

Promise.all([
  faceapi.nets.tinyFaceDetector.loadFromUri('/models'),
  faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
  faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
  faceapi.nets.faceExpressionNet.loadFromUri('/models'),
]).then(startVideo)

function startVideo() {
  navigator.getUserMedia(
    { video: {} },
    stream => video.srcObject = stream,
    err => console.error(err)
  )
}

Upvotes: 3

Views: 4726

Answers (1)

haldo
haldo

Reputation: 16701

There are a couple of methods listed on the mediaDevices.getUserMedia() MDN page. You can access the mediaDevices object like this:

async function getMedia(constraints) {
  let stream = null;

  try {
    stream = await navigator.mediaDevices.getUserMedia(constraints);
    /* use the stream */
  } catch(err) {
    /* handle the error */
  }
}

Or use the promises directly:

navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
  /* use the stream */
})
.catch(function(err) {
  /* handle the error */
});

The below is adapted from the Examples section:

var constraints = { audio: true, video: true }; 

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

Upvotes: 5

Related Questions