7

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

Breaker222
  • 1,334
  • 1
  • 14
  • 23

2 Answers2

6

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

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

Philipp Hancke
  • 15,855
  • 2
  • 23
  • 31
  • "There is no list kept by the browser" might answer my background question (see edit), so I'll accept this as the answer. – Breaker222 Jun 20 '16 at 21:07
5

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.

jib
  • 40,579
  • 17
  • 100
  • 158