Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get running mediaStream

I've created a webCam Stream with

navigator.getUserMedia({ "video": true }, function(stream){
    videoTag.src = window.URL.createObjectURL(stream);
    videoTag.play();
}

Can I access the MediaStream object in stream in global scope?*

(something like navigator.getAllMediaStreams[0])

*edit: ...without adding logic to the getUserMedia function. My problem case is a qr-decoder-library, that gets the stream for me and I don't want to change the third party code

like image 309
Breaker222 Avatar asked Jun 20 '16 19:06

Breaker222


2 Answers

There is no list of active media streams kept by the browser.

You can save the stream to for example window.stream.

like image 119
Philipp Hancke Avatar answered Sep 27 '22 17:09

Philipp Hancke


Sure:

navigator.allMediaStreams = [];

navigator.mediaDevices.getUserMedia({ "video": true }).then(stream => {
  navigator.allMediaStreams.push(stream);
  console.log(navigator.allMediaStreams.length); // 1
})
.catch(e => console.error(e));

console.log(navigator.allMediaStreams.length); // 0

Just understand that the array will be empty until the success callback fires.

It's like any other JavaScript object. As long as you keep a reference to a stream (so it doesn't get garbage collected), and don't call stop() on its tracks, you'll have a live video stream at your disposal, and the active-camera light, if there is one, will be on during this time.

Also like any other JavaScript variable, it is still tied to the page, even if it hangs off navigator, so it won't survive page navigation.

like image 20
jib Avatar answered Sep 27 '22 16:09

jib