So far I have successfully established (running node.js server) an RTC connection between two peers with a datachannel. I can send data back and forth.
I have also successfully streamed the webcam from one peer to another and vice versa. How exactly am I doing this?
Both peers do this:
function handleRemoteStreamAdded(event) {
console.log('Remote stream added.');
remoteStream = event.stream;
remoteVideo.srcObject = remoteStream;
}
function gotStream(stream){
...
pc.addStream(stream);
...
}
navigator.mediaDevices.getUserMedia(constraints).then(gotStream).catch(err);
...
pc = new RTCPeerConnection();
...
pc.onaddstream = handleRemoteStreamAdded;
So I basically say that whenever I add my own stream (pc.addStream) then go to handleRemoteStreamAdded. It all works fine.
But what I really want to do as a next step is to add a button to each client and give each of them the option whether or not they want to stream their cam to the other side. If they want to, then the stream should start automatically on the other end. Unfortunately, I just can't figure out how to.
Theoretically, what I thought is to add an Eventlistener to a button and then the event triggers:
navigator.mediaDevices.getUserMedia(constraints).then(gotStream).catch(err);
By doing this I basically also did pc.addStream(stream);
via function gotStream
. Then I send a message to the other end like "display my cam" and by receiving this message on the other end, that other peer should somehow trigger handleRemoteStreamAdded
. But within this function there is the pre-defined event
that I can only "access" locally via pc.onaddstream = handleRemoteStreamAdded;
How can I automatically start streaming the other side's cam as soon as I either get a message like "display my cam" or by some event?