we need to separate the audio from two peerconnections into two different output devices.
Each peerconnection receives the corresponding audio track.
we have two audio elements, one for each peerconnection.
By making use of setsinkid of an audio element assigned to peerconnection1, it also affects the audio output element assigned to peerconnection2 preventing each stream to be played by a different output device from the other peerconnection.
For each ontrack event of each peerconnection, we create a new mediastream and add the track to the mediastream.
Checking the browser's webrtc-internals viewer, I check that both peerconnection share the same RTCMediaStream element but each one with its corresponding track.
var localStream = await navigator.mediaDevices.getUserMedia({vide: true, audio: true});
peerConnection1 = new RTCPeerConnection(config);
localStream.getTracks().forEach(track => {
peerConnection1.addTrack(track, localStream);
});
var remoteStream = new MediaStream();
var remote = document.querySelector('#audio1');
remoteVideo.srcObject = remoteStream;
peerConnection1.addEventListener('track', async (event) => {
remoteStream.addTrack(event.track, remoteStream);
});
peerConnection1.addEventListener('icecandidate', event => {
if (event.candidate) {
ws.sendMessage({
id: 'ADD_ICE_CANDIDATE_SELECT',
candidate: event.candidate
});
}});
var sdpOffer = await peerConnection1.createOffer();
await peerConnection1.setLocalDescription(sdpOffer);
ws.onmessage = function(message)
{
switch (jsonMessage.id) {
case 'PROCESS_SDP_ANSWER_PEER1':
var remoteDesc = new RTCSessionDescription({type:"answer",sdp:jsonMessage.sdpAnswer});
await peerConnection1.setRemoteDescription(remoteDesc);
break;
case 'ADD_ICE_CANDIDATE_PEER1':
await peerConnection1.addIceCandidate(jsonMessage.candidate);;
break;
};
ws.sendMessage({
id: 'PROCESS_SDP_OFFER_PEER1',
sdpOffer: sdpOffer.sdp
});