4

If your app wants to get the same user media, say the audio with the exact same constraints, more than once, will navigator.mediaDevices.getUserMedia call return a new stream, so will allocate same amount of computing resources, or will it just give you the same stream (same object with same reference) hence do not uses extra resources?

I am tarnsmitting the user's audio stream to another user of the app. At some point a third or more users will join and they need the same audio from the first user that the first user is transmitting to the second user to be transmitted to themselves.

I want to be as efficient as not allocating new resources for the copy of the same audio stream.

Should I call navigator.mediaDevices.getUserMedia again and it will give me the same stream (same reference) it has given me before, or should I not do that since it will give me a new audio stream even the constraints I have supplied are the exact same, and I should just reuse the previously returned audio stream by a way such as storing it in a variable in reach?

My investigations show that the streams', MediaStream objects') ids are different. It looks like they are different objects.

const str = await navigator.mediaDevices.getUserMedia({audio: true})
MediaStream {  ​
active: true    ​
id: "{f3b334cd-8507-408f-94e9-40b42bbd73f6}"
...
}

const str1 = await navigator.mediaDevices.getUserMedia({audio: true})
MediaStream {
active: true
id: "{ec94325c-19d8-4e91-b668-636f3c267ad4}"
​...
}

Also a call to Object.is(str, st1) returns false.

sçuçu
  • 2,960
  • 2
  • 33
  • 60

1 Answers1

5

The deep truth of the answer to your question lies in browser implementation details. (Meaning: trying to reverse-engineer how it is supposed to work from how it does work is, umm, difficult.)

If you're using WebRTC's communications, you can give the same stream object, from a single call to getUserMedia(), to multiple peer connection objects and they'll all get the stream data.

You can do stream.clone() to clone the stream if you wish. Stream clones have new id values.

As far as calling .getUserMedia() multiple times, it fails in some browser situations if you do it without doing track.stop() on the tracks of an existing stream. Giving different constraints to different calls also causes failure.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • "If you're using WebRTC's communications, you can give the same stream object, from a single call to getUserMedia(), to multiple peer connection objects and they'll all get the stream data." That was the answer to the ultimate or leading question I would need. Thanks! I guess for my use case I just need same stream, and sometimes same stream with additional tracks from another stream. But still we do not if it is the same or another stream for my question, though it does not matter for my use case if the way I have quoted works, but only for the knowing the truth. What does the spec suggest? – sçuçu Jul 27 '20 at 17:45