forked from divanov11/WebRTC-Simple-SDP-Handshake-Demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
67 lines (52 loc) · 2.16 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
let peerConnection = new RTCPeerConnection()
let localStream;
let remoteStream;
let init = async () => {
localStream = await navigator.mediaDevices.getUserMedia({video:true, audio:false})
remoteStream = new MediaStream()
document.getElementById('user-1').srcObject = localStream
document.getElementById('user-2').srcObject = remoteStream
localStream.getTracks().forEach((track) => {
peerConnection.addTrack(track, localStream);
});
peerConnection.ontrack = (event) => {
event.streams[0].getTracks().forEach((track) => {
remoteStream.addTrack(track);
});
};
}
let createOffer = async () => {
peerConnection.onicecandidate = async (event) => {
//Event that fires off when a new offer ICE candidate is created
if(event.candidate){
document.getElementById('offer-sdp').value = JSON.stringify(peerConnection.localDescription)
}
};
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
}
let createAnswer = async () => {
let offer = JSON.parse(document.getElementById('offer-sdp').value)
peerConnection.onicecandidate = async (event) => {
//Event that fires off when a new answer ICE candidate is created
if(event.candidate){
console.log('Adding answer candidate...:', event.candidate)
document.getElementById('answer-sdp').value = JSON.stringify(peerConnection.localDescription)
}
};
await peerConnection.setRemoteDescription(offer);
let answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
}
let addAnswer = async () => {
console.log('Add answer triggerd')
let answer = JSON.parse(document.getElementById('answer-sdp').value)
console.log('answer:', answer)
if (!peerConnection.currentRemoteDescription){
peerConnection.setRemoteDescription(answer);
}
}
init()
document.getElementById('create-offer').addEventListener('click', createOffer)
document.getElementById('create-answer').addEventListener('click', createAnswer)
document.getElementById('add-answer').addEventListener('click', addAnswer)