pion/webrtc
by Vladimir Vershinin
HTML
Browser Session Description<br>
<textarea id="localSessionDescription" readonly style="width: 100%; height: 300px"></textarea><br>
Golang Session Description<br>
<textarea id="remoteSessionDescription" readonly style="width: 100%; height: 300px"></textarea><br>
<button id="start-sess" onclick="window.startSession()">Start Session</button>
<button id="stop-sess" onclick="window.stopSession()" style="display: none">Stop Session</button>
<br>
<br>
<audio id="audio1" autoplay></audio>
<br>
<br>
Logs<br>
<div id="logs"></div>
JavaScript
const log = msg => {
document.getElementById('logs').innerHTML += msg + '<br>'
}
let convID, pc
window.startSession = () => {
pc = new RTCPeerConnection({
iceServers: [{
urls: 'stun:stun.l.google.com:19302'
}]
})
document.getElementById('start-sess').innerText = 'connecting...'
document.getElementById('start-sess').disabled = true
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
})
.then(stream => {
stream.getTracks().forEach(track => pc.addTrack(track, stream))
let {
codecs
} = RTCRtpSender.getCapabilities('audio')
codecs = codecs.filter(codec => ['audio/PCMU', 'audio/PCMA'].includes(codec.mimeType))
const transceiver = pc.getTransceivers().find(t => t.sender && t.sender.track === stream.getAudioTracks()[0])
transceiver.setCodecPreferences(codecs)
return pc.createOffer()
})
.then(d => pc.setLocalDescription(d))
.catch(log)
pc.oniceconnectionstatechange = () => log(pc.iceConnectionState)
pc.onicecandidate = event => {
if (event.candidate === null) {
document.getElementById('localSessionDescription').value = 'Type: ' + pc.localDescription.type + '\n\n' + pc.localDescription.sdp
fetch('https://fc30202f9050.ngrok.io/invite', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(pc.localDescription),
})
.then(res => res.json())
.then(res => {
document.getElementById('start-sess').innerText = 'Start session'
document.getElementById('start-sess').disabled = false
document.getElementById('start-sess').style.display = 'none'
document.getElementById('stop-sess').style.display = 'inline'
convID = res.conversation_id
return pc.setRemoteDescription(new RTCSessionDescription(res.session_description))
})
.then(() => {
...