Creating a real-time video and audio call application involves utilizing WebRTC for peer-to-peer media streaming and a signaling server (often using technologies such as Socket.io) for setting up the WebRTC connections. Below, I'll guide you through creating a simple video/audio call app using Node.js and WebRTC.
Overview of the System
- WebRTC: Handles the actual peer-to-peer audio and video stream.
- Socket.io: Used as a signaling server to exchange metadata and initiate WebRTC connections.
- Simple frontend: Interaction with the browser's media APIs and WebRTC.
Basic Setup
Here's a more concrete example to get you started:
1. Server Setup
First, set up your basic Node.js server for signaling:
mkdir webrtc-video-call
cd webrtc-video-call
npm init -y
npm install express socket.io
Create the server.js:
// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
// Signaling code using Socket.io
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('offer', (data) => {
socket.to(data.target).emit('offer', data);
});
socket.on('answer', (data) => {
socket.to(data.target).emit('answer', data);
});
socket.on('candidate', (data) => {
socket.to(data.target).emit('candidate', data);
});
socket.on('join', (roomId) => {
socket.join(roomId);
socket.to(roomId).emit('new-member', { id: socket.id });
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
2. Client Setup
In the public directory, create the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebRTC Video Call</title>
<style>
video {
width: 300px;
border: 2px solid black;
margin: 10px;
}
</style>
</head>
<body>
<h1>Video Call with WebRTC</h1>
<video id="localVideo" autoplay playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>
<button id="startCall" disabled>Start Call</button>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
const startCallButton = document.getElementById('startCall');
let localStream;
let peerConnection;
const configuration = {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
};
// Get video/audio stream from user's device
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
localVideo.srcObject = stream;
localStream = stream;
startCallButton.disabled = false;
})
.catch(error => console.error('Error accessing media devices.', error));
// Create PeerConnection and handle ICE candidates
function createPeerConnection() {
peerConnection = new RTCPeerConnection(configuration);
peerConnection.onicecandidate = ({ candidate }) => {
if (candidate) {
socket.emit('candidate', { target: partnerId, candidate });
}
};
peerConnection.ontrack = (event) => {
remoteVideo.srcObject = event.streams[0];
};
localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
}
// Start call and create offer
startCallButton.onclick = () => {
socket.emit('join', 'room1');
};
socket.on('new-member', ({ id }) => {
partnerId = id;
createPeerConnection();
peerConnection.createOffer()
.then(offer => peerConnection.setLocalDescription(offer))
.then(() => {
socket.emit('offer', { target: partnerId, sdp: peerConnection.localDescription });
});
});
socket.on('offer', (data) => {
createPeerConnection();
peerConnection.setRemoteDescription(new RTCSessionDescription(data.sdp))
.then(() => peerConnection.createAnswer())
.then(answer => peerConnection.setLocalDescription(answer))
.then(() => {
socket.emit('answer', { target: data.id, sdp: peerConnection.localDescription });
});
});
socket.on('answer', (data) => {
peerConnection.setRemoteDescription(new RTCSessionDescription(data.sdp));
});
socket.on('candidate', (data) => {
peerConnection.addIceCandidate(new RTCIceCandidate(data.candidate));
});
</script>
</body>
</html>
How It Works:
- Media Stream Setup: Using
navigator.mediaDevices.getUserMedia to access webcam and microphone for video/audio streams.
- Signaling via Socket.io: Exchanging offers, answers, and ICE candidates through the server to establish connections between peers.
- WebRTC Peer Connections: Managing the negotiation and connection handling using the WebRTC API (
RTCPeerConnection).
Running Your Application
-
Start the Server:
Make sure your server is running by executing:
node server.js
-
Access the App:
Open your browser and go to http://localhost:3000. Use two different browser windows or different devices to test calling each other.
Notes:
- STUN/TURN Servers: Using a STUN server (
stun:stun.l.google.com:19302) helps peers discover each other's public addresses. For complete production setups, especially with NATs and firewalls, use TURN servers too.
- Security: This is a simple example. In production, you must implement proper security measures, HTTPS, and possibly authentication and room management.
- Production Considerations: This example is very simplified. Real-world applications need additional code for room management, better signaling (e.g., using unique room IDs), and handling edge cases like peer disconnection.
This sample should help you get started with building a basic video and audio call app using WebRTC and Node.js, with Socket.io handling signaling.