I tried to do a simple WebRTC p2p video chat browser app. I setup a signal server and have two peers doing all the SDP and ICE handshakes. Some of my code snippet:
pc = new RTCPeerConnection(config);
pc.onicecandidate = (event) => {
...
}
pc.ontrack(event) =>{
if (event.track.kind === 'video') {
// add the stream as the srcObject of a video tag
}
event.streams[0].onremovetrack = (e) => {
// want to remove the stream from the video tag
}
}
When a peer is done I do the following:
pc.stop();
I simply just close the RTCPeerConnection. But I don't see the onremovetrack being triggered on the other peer.
What is the proper way to shutdown a peer so that the other peer can be notified and onremovetrack triggered?
I think you should use the
RTCPeerConnection.removeTrack()method, it will fire theMediaStream.onremovetrackevent at the other end.To get the tracks of the connection use the
RTCPeerConnection.getSenders()method.Example
This will remove all the tracks from the connection. There's an experimental method to completely close the connection,
RTCPeerConnection.close(), check the compatibility table. Use it after the tracks removed, so you will get theonremovetrackevents:Alternative
The other way is to immediately call the
close()method and listen to theRTCPeerConnection.onconnectionstatechangeevent at the other end, check the example.More information
getSenders()methodremoveTrack()methodonremovetrackevent handlerclose()methodonconnectionstatechangeevent handler