Skip to content

Instantly share code, notes, and snippets.

@Vatsalya-singhi
Last active August 10, 2020 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vatsalya-singhi/29ba029f869a5035b1503a6db80f0fa3 to your computer and use it in GitHub Desktop.
Save Vatsalya-singhi/29ba029f869a5035b1503a6db80f0fa3 to your computer and use it in GitHub Desktop.
public offerListener() {
this.socket.offerListen()
.pipe(takeWhile(() => this.alive))
.subscribe(async (data) => {
// receive user id and peer offer
let id: string = data.id;
let offer: RTCSessionDescription = data.offer;
if (!this.peerConnections[id] || this.peerConnections[id] == null) {
this.peerConnections[id] = new RTCPeerConnection(this.connectionConfig);
}
this.peerConnections[id]
.setRemoteDescription(offer)
.then(() => {
// get current user media stream
return this.getUserMediaCommonFunctionCall(id, 2);
})
.then((stream: MediaStream) => {
this.userVideo.srcObject = stream;
})
.then(() => {
// create answer
if (!this.peerConnections[id].localDescription || this.peerConnections[id].localDescription == null) {
return this.peerConnections[id].createAnswer();
}
throw "answer created already";
})
.then((answer: RTCSessionDescriptionInit) => {
return this.peerConnections[id].setLocalDescription(answer);
})
.then(() => {
//send back answer to the requester peer
this.socket.sendAnswer(id, this.peerConnections[id].localDescription);
})
.catch((err) => {
console.error('err=>', err);
});
this.peerConnections[id].ontrack = (event: RTCTrackEvent) => {
if (otherVidElement) {
// add stream from requester
if (!otherVidElement.srcObject) {
otherVidElement.srcObject = event.streams[0];
}
// event listener to check if stream has ended
event.track.onended = (event: Event) => {
console.log('track ended!');
otherVidElement.srcObject = otherVidElement.srcObject;
}
}
};
}, (err) => {
console.log('err=>', err);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment