I'm working on a WebRTC application where I dynamically add audio tracks to a peerConnection
after obtaining microphone permissions. I want to avoid adding duplicate tracks to prevent unnecessary signaling and offers. However, I've noticed that the track.id
changes each time I call getUserMedia
, making it difficult to check if a track has already been added.
Here's the code I'm using to add tracks
const localStream = await navigator.mediaDevices.getUserMedia({
video: false,
audio: true,
})
localStream.getAudioTracks().forEach((track) => {
mapPeerConnection.forEach((peerConnection, userId) => {
peerConnection.addTrack(track, localStream)
sendOffer(userId) //Emit offer to start WebRTC connection
})
})
There is no direct way to accomplish this. You can try to iterate over the RTP sender objects of the peerconnection using
pc.getSenders.forEach(sender => {
// sender.track might be set or null and if not null might be stopped
})
and compare the track label and kind. You can also check the deviceId
and groupId
returned from the track.getSettings()
An alternative to consider is structuring your code in such a way that your microphone is always on the first transceiver, your webcam on the second and outgoing screen sharing streams on the third and fourth respectively. That way you know what transceiver (or slot) to attach the result of getUserMedia to (or whether you need to call getUserMedia in the first place)