-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebrtc.html
36 lines (36 loc) · 2.11 KB
/
webrtc.html
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
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<input id="server" value="https://" />
<input id="source" type="file" />
<button id="open">Open</button>
<button id="stop">Stop</button>
<button id="upload">SourceImage</button><br>
<video id="real" autoplay></video>
<video id="fake" autoplay></video>
<script>
const DID = _ => document.getElementById(_)
document.head.append(Object.assign(document.createElement('style'), { textContent: `video{width:100%;height:auto} #source{display:none}` }))
DID("open").onclick = () => navigator.mediaDevices.getUserMedia({ video: true, audio: false }).then(async stream => {
const pc = new RTCPeerConnection({ iceServers: [{ urls: "stun:stun.l.google.com:19302" }] })
let params = { candidates: [] }
let timer
(DID("real").srcObject = stream).getTracks().forEach(_ => pc.addTrack(_, stream))
await pc.setLocalDescription(await pc.createOffer())
params.sdp = pc.localDescription.sdp
pc.ontrack = (event) => DID("fake").srcObject = event.streams[0]
pc.onicecandidate = ({ candidate }) => {
if (candidate) {
clearTimeout(timer)
params.candidates.push(candidate)
timer = setTimeout(() => fetch(DID("server").value, { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params) }).then(_ => _.json()).then((data) => data.type === 'answer' && pc.setRemoteDescription(new RTCSessionDescription(data))), 1000)
}
}
DID("stop").onclick = () => (pc.close(), ["real", "fake"].forEach(_ => (DID(_).srcObject?.getTracks()?.forEach(_ => _.stop()), DID(_).srcObject = null)))
})
DID("upload").onclick = () => DID("source").click()
DID("source").addEventListener("change", ({ target: { files: [file] } }) => {
const reader = new FileReader()
reader.onload = (e) => fetch(DID("server").value + "/src", { method: "POST", body: e.target.result }).then(_ => _.json()).then(({ status }) => alert(status))
reader.readAsArrayBuffer(file)
DID("source").value = ""
})
</script>