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);
// Send offer to server
const response = await fetch('/offer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
sdp: offer.sdp,
type: offer.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: