Files
go2rtc/www/webrtc.html
T
2023-03-19 17:17:05 +03:00

81 lines
2.4 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>go2rtc - WebRTC</title>
<style>
body {
background-color: black;
margin: 0;
padding: 0;
}
html, body, video {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<video id="video" autoplay controls playsinline muted></video>
<script>
function PeerConnection(userMedia) {
const pc = new RTCPeerConnection({
iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
})
document.getElementById('video').srcObject = new MediaStream([
pc.addTransceiver('video', {direction: 'recvonly'}).receiver.track,
pc.addTransceiver('audio', {direction: 'recvonly'}).receiver.track
])
if (userMedia) {
userMedia.getTracks().forEach(track => {
pc.addTransceiver(track, {direction: 'sendonly'})
})
}
return pc
}
async function userMedia() {
try {
return await navigator.mediaDevices.getUserMedia({audio: true})
} catch (e) {
return null
}
}
async function connect() {
const pc = PeerConnection(await userMedia())
const url = new URL('api/ws' + location.search, location.href)
const ws = new WebSocket('ws' + url.toString().substring(4))
ws.addEventListener('open', () => {
pc.addEventListener('icecandidate', ev => {
if (!ev.candidate) return
const msg = {type: 'webrtc/candidate', value: ev.candidate.candidate}
ws.send(JSON.stringify(msg))
})
pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => {
const msg = {type: 'webrtc/offer', value: pc.localDescription.sdp}
ws.send(JSON.stringify(msg))
})
})
ws.addEventListener('message', ev => {
const msg = JSON.parse(ev.data)
if (msg.type === 'webrtc/candidate') {
pc.addIceCandidate({candidate: msg.value, sdpMid: '0'})
} else if (msg.type === 'webrtc/answer') {
pc.setRemoteDescription({type: 'answer', sdp: msg.value})
}
})
}
connect()
</script>
</body>
</html>