Here's the minimal code needed to establish a WebRTC connection with audio and data channel:
async function setupWebRTC() {
try {
// Get audio stream
const localStream = await navigator.mediaDevices.getUserMedia({
audio: true
});
// Create peer connection
const peerConnection = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});
// Add audio track
const audioTrack = localStream.getAudioTracks()[0];
peerConnection.addTrack(audioTrack, localStream);
// Create data channel
const dataChannel = peerConnection.createDataChannel("text");
dataChannel.onopen = () => dataChannel.send("handshake");
// Create and send offer
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
// wait for ice gathering to complete
await new Promise((resolve) => {
if (peerConnection.iceGatheringState === "complete") {
resolve();
} else {
const checkState = () => {
if (peerConnection.iceGatheringState === "complete") {
peerConnection.removeEventListener("icegatheringstatechange", checkState);
resolve();
}
};
peerConnection.addEventListener("icegatheringstatechange", checkState);
}
});
// Send offer to server
const response = await fetch('/offer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sdp: peerConnection.localDescription.sdp,
type: peerConnection.localDescription.type,
webrtc_id: Math.random().toString(36).substring(7)
})
});
// Handle server response
const serverResponse = await response.json();
await peerConnection.setRemoteDescription(new RTCSessionDescription({
type: serverResponse.type,
sdp: serverResponse.sdp
}));
} catch (error) {
console.error('Connection error:', error);
}
}
Call this function when you want to establish the connection:
// Create a button to start the connection
document.getElementById('connectButton').onclick = setupWebRTC;
This implementation includes: