maxpaj
maxpaj

Reputation: 6771

MediaStream reference not removed / why does my webcam stay busy?

Background / Issue

Using navigator.mediaDevices.getUserMedia(constraints) I can obtain a MediaStream object for various devices, amongst them webcam and microphone, allowing you to do whatever you want with the data that comes through.

The method getUserMedia returns a Promise which resolve to a media stream or rejects if there is no stream available for the given constraints (video, audio etc.) If I do obtain a stream object BUT don't save any reference to the MediaStream - I understand that the garbage collector should remove it.

What I've observed is that the stream is not removed - if I obtain a stream for the webcam for example, it keeps being busy even though I have no reference left to the stream.

Questions

  1. Where is the MediaStream object stored if I don't save a reference to it?
  2. Why is it not removed by the garbage collector?
  3. Why does my webcam stay busy?

Upvotes: 2

Views: 1068

Answers (1)

Mat
Mat

Reputation: 1091

The MediaStream API requires you to stop each track contained in the MediaStream instance that you obtained. Until you do so, the media capture will keep going.

navigator.mediaDevices
  .getUserMedia({
    audio: true,
    video: true
  })
  .then(function (stream) {
    console.log('got stream with id ' + stream.id)
    stream.getTracks().forEach(function (track) { track.stop() })
    // WebCam will not be busy anymore
  })
  .catch(function (reason) {
    console.error('capture failed ' + reason)
  })

Upvotes: 3

Related Questions