6

I am trying to implement video recording but getting this error. i have 2 buttons called Front Camera ,Back Camera. On click i am calling below method. first it displays the camera correctly but while switching camera it gives me the error. Please help how to fix the problem ?

function StartVideoCamera(obj) {
    var id = $(obj).attr('id');
    var camNode = $(obj).attr('cammode');
    if (camNode != 'user') {
        camNode = eval('{ exact: "environment" }')
    }
    var video = document.querySelector('#video' + id);
    var constraints = { audio: true, video: { width: videoHeight, height: videoWidth, facingMode: camNode 
    } };
    navigator.mediaDevices.getUserMedia(constraints)
    .then(function (mediaStream) {
        window.stream = null;
        video.srcObject = null;
        recordButton.disabled = false;
        window.stream = mediaStream;
        video.srcObject = mediaStream;
        video.onloadedmetadata = function (e) {
            video.play();
        };
    })
    .catch(function (err) {
         alert(err.name + ": " + err.message)
         console.log(err.name + ": " + err.message);
     });
}
santosh
  • 61
  • 1
  • 1
  • 4
  • Does this answer your question? [NotReadableError: Could not start source](https://stackoverflow.com/questions/48775154/notreadableerror-could-not-start-source) – isAif Dec 30 '20 at 12:14
  • 9
    This error usually occurs when either your camera is being used by some other application or you try to stream from a different camera before closing the existing camera stream. So i need to stop the stream first . Suggested codes are below – santosh Dec 30 '20 at 12:31
  • 7
    const tracks = stream.getTracks(); tracks.forEach(track => track.stop()); – santosh Dec 30 '20 at 12:32
  • But how to write these codes here ? – santosh Dec 30 '20 at 12:32
  • As @santosh points out, this might happen when you try to streamm from a different camera before closing the existing camera stream. I was using the library HTML5 QR (https://github.com/mebjas/html5-qrcode) AND from the PC, if you paused the existing camerastream and tried to stream from a new one, it would work well. However this wasn't the case in Android. (same browsers). Followed his comment and stopped the previous camera stream it before trying to acces a new one; works like a charm now. Thank you. – Manuel Jun 13 '22 at 12:46

1 Answers1

5

You need to stop the previous mediaStreamObj before calling getUserMedia again.

This happens when your other(front/back) is already in use. You need to release the camera first.

stream.getTracks()
.forEach(track => track.stop());

Here stream is what you got from getUserMedia

This stops all the devices (you can check that the camera light goes off on the desktop) and (on mobile devices).

Shakil Alam
  • 308
  • 4
  • 9