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

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

什么是 WebRTC?

WebRTC(Web Real-Time Communication)是一个支持浏览器之间实时通信的 API。

WebRTC 的组成

API 功能
MediaStream 访问摄像头和麦克风
RTCPeerConnection 建立点对点连接
RTCDataChannel 数据通道

获取媒体流

javascript 复制代码
async function getMediaStream() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    });
    return stream;
  } catch (error) {
    console.error('获取媒体流失败:', error);
  }
}

显示视频流

html 复制代码
<video id="localVideo" autoplay playsinline></video>
javascript 复制代码
const video = document.getElementById('localVideo');
const stream = await getMediaStream();
video.srcObject = stream;

建立点对点连接

javascript 复制代码
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 });

信令服务器

javascript 复制代码
// 简易信令服务器
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);
      }
    });
  });
});

处理远程流

javascript 复制代码
peerConnection.ontrack = (event) => {
  const remoteVideo = document.getElementById('remoteVideo');
  remoteVideo.srcObject = event.streams[0];
};

// 接收 Answer
peerConnection.setRemoteDescription(answer);

数据通道

javascript 复制代码
const dataChannel = peerConnection.createDataChannel('chat');

dataChannel.onopen = () => {
  dataChannel.send('Hello from WebRTC!');
};

dataChannel.onmessage = (event) => {
  console.log('收到消息:', event.data);
};

STUN 和 TURN 服务器

javascript 复制代码
const configuration = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    {
      urls: 'turn:turn.example.com:3478',
      username: 'user',
      credential: 'password'
    }
  ]
};

错误处理

javascript 复制代码
peerConnection.oniceconnectionstatechange = () => {
  if (peerConnection.iceConnectionState === 'failed') {
    console.error('连接失败,尝试重新连接');
  }
};

peerConnection.onicegatheringstatechange = () => {
  if (peerConnection.iceGatheringState === 'complete') {
    console.log('ICE 候选收集完成');
  }
};

实战案例

视频通话应用

javascript 复制代码
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 为实时通信提供了强大的能力:

  1. 浏览器原生支持:无需插件
  2. 低延迟:直接点对点连接
  3. 数据通道:支持文本和二进制数据
  4. 跨平台:支持桌面和移动浏览器

掌握 WebRTC,构建实时音视频应用。

相关推荐
墨舟的AI笔记22 分钟前
React 组件库的 Tree Shaking:按需加载与副作用的工程化治理
人工智能
曦尧29 分钟前
Microsoft Ontology Playground:用纯前端工具打通 Fabric IQ 本体论学习通路
ai·自动化
WoooChi1 小时前
DailyTech-20260724
人工智能·科技·业界资讯
zh路西法1 小时前
【CAM Grad-CAM Grad-CAM++】深度学习模型可解释性:从原理到YOLOv8部署实战
人工智能·深度学习·yolo·yolov8·grad-cam·cam
雨辰AI2 小时前
全集实战:企业级大模型服务化部署全栈指南|FastAPI 封装 + Nginx 负载均衡 + 高可用架构 从单机到生产一步到位
人工智能·ai·负载均衡·fastapi·ai编程
触底反弹2 小时前
Vibe Coding 不写 Git,等于悬崖边飙车
人工智能·git·面试
咖啡屋和酒吧2 小时前
健康管理:现代生活的科学守护
人工智能·生活·精选
星栈独行2 小时前
翻完 Pi 源码:它和 Codex、Claude Code 有何不同
开发语言·javascript·人工智能·程序人生
没有梦想的咸鱼185-1037-16632 小时前
AI-Python机器学习与深度学习技术:CNN/Transformer/扩散模型、SHAP可解释及Hermes智能体自动化
人工智能·python·深度学习·机器学习·chatgpt·cnn·transformer
船漏了就会沉3 小时前
Kimi K3 vs DeepSeek-V4:国产大模型的技术路线之争
人工智能