WebRTC 实时通信:构建音视频通话应用

WebRTC 实时通信:构建音视频通话应用 WebRTC 实时通信构建音视频通话应用什么是 WebRTCWebRTCWeb Real-Time Communication是一个支持浏览器之间实时通信的 API。WebRTC 的组成API功能MediaStream访问摄像头和麦克风RTCPeerConnection建立点对点连接RTCDataChannel数据通道获取媒体流async function getMediaStream() { try { const stream await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); return stream; } catch (error) { console.error(获取媒体流失败:, error); } }显示视频流video idlocalVideo autoplay playsinline/videoconst video document.getElementById(localVideo); const stream await getMediaStream(); video.srcObject stream;建立点对点连接const peerConnection new RTCPeerConnection({ iceServers: [ { urls: stun:stun.l.google.com:19302 } ] }); // 添加本地流 stream.getTracks().forEach(track { peerConnection.addTrack(track, stream); }); // 创建 Offer const offer await peerConnection.createOffer(); await peerConnection.setLocalDescription(offer); // 发送 Offer 到信令服务器 sendToServer({ type: offer, data: offer });信令服务器// 简易信令服务器 const WebSocket require(ws); const wss new WebSocket.Server({ port: 8080 }); wss.on(connection, (ws) { ws.on(message, (data) { wss.clients.forEach((client) { if (client ! ws client.readyState WebSocket.OPEN) { client.send(data); } }); }); });处理远程流peerConnection.ontrack (event) { const remoteVideo document.getElementById(remoteVideo); remoteVideo.srcObject event.streams[0]; }; // 接收 Answer peerConnection.setRemoteDescription(answer);数据通道const dataChannel peerConnection.createDataChannel(chat); dataChannel.onopen () { dataChannel.send(Hello from WebRTC!); }; dataChannel.onmessage (event) { console.log(收到消息:, event.data); };STUN 和 TURN 服务器const configuration { iceServers: [ { urls: stun:stun.l.google.com:19302 }, { urls: turn:turn.example.com:3478, username: user, credential: password } ] };错误处理peerConnection.oniceconnectionstatechange () { if (peerConnection.iceConnectionState failed) { console.error(连接失败尝试重新连接); } }; peerConnection.onicegatheringstatechange () { if (peerConnection.iceGatheringState complete) { console.log(ICE 候选收集完成); } };实战案例视频通话应用class VideoCall { constructor() { this.peerConnection null; this.localStream null; } async start() { this.localStream await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); this.setupPeerConnection(); this.connectToSignaling(); } setupPeerConnection() { this.peerConnection new RTCPeerConnection({ iceServers: [{ urls: stun:stun.l.google.com:19302 }] }); this.localStream.getTracks().forEach(track { this.peerConnection.addTrack(track, this.localStream); }); } }总结WebRTC 为实时通信提供了强大的能力浏览器原生支持无需插件低延迟直接点对点连接数据通道支持文本和二进制数据跨平台支持桌面和移动浏览器掌握 WebRTC构建实时音视频应用。