You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PeerJS connection已弃用:视频聊天应用屏幕共享流更新问题

问题描述

我正在开发一款视频聊天应用,需要实现屏幕共享功能。问题在于进行屏幕共享时,更新后的MediaStream无法通过“connection”方法同步给其他对等端,我需要一种能替换所有已连接对等端当前流的方案。以下是相关代码,其中提示connection已弃用:

const switchStream = (stream: MediaStream) => {
  setStream(stream);

  // 需为每个连接替换当前流
  // 先检查currentPeer及currentPeer.connections是否存在
  if (currentPeer && currentPeer.connections) {
    // 遍历每个连接
    Object.values(currentPeer.connections).forEach((connection: any) => {
      // 在流中找到视频轨道
      const videoTrack: any = stream
        ?.getTracks()
        .find((track: any) => track.kind === "video");

      // 为连接中的每个发送者替换视频轨道
      connection[0].peerConnection.getSenders().forEach((sender: any) => {
        if (sender.track && sender.track.kind === "video") {
          sender
            .replaceTrack(videoTrack)
            .catch((err: any) => console.error(err));
        }
      });
    });
  } else {
    console.error("currentPeer or currentPeer.connections is undefined.");
  }
};
解决方案

核心思路:手动维护RTCPeerConnection实例列表

既然currentPeer.connections已被弃用,不要依赖这个属性,改为自己管理所有已建立的RTCPeerConnection实例集合。直接遍历这个集合替换视频轨道,既符合现代WebRTC规范,也能避免弃用API带来的兼容性问题。

具体实现步骤

  1. 先在模块或组件内维护一个活跃的PeerConnection数组:
// 存储所有已建立连接的RTCPeerConnection实例
const activePeerConnections: RTCPeerConnection[] = [];
  1. 创建新连接时,将实例加入数组:
// 示例:创建PeerConnection并加入列表
const createNewPeerConnection = (config: RTCConfiguration) => {
  const pc = new RTCPeerConnection(config);
  activePeerConnections.push(pc);
  // 其他初始化逻辑(如添加ICE候选、监听媒体流等)
  return pc;
};
  1. 优化后的流切换函数:
const switchStream = (stream: MediaStream) => {
  setStream(stream);

  if (!stream) {
    console.error("传入的流无效");
    return;
  }

  // 获取屏幕共享的视频轨道
  const videoTrack = stream.getVideoTracks()[0];
  if (!videoTrack) {
    console.error("流中未找到视频轨道");
    return;
  }

  // 遍历所有活跃连接,替换视频轨道
  activePeerConnections.forEach(pc => {
    pc.getSenders().forEach(sender => {
      if (sender.track?.kind === "video") {
        sender.replaceTrack(videoTrack)
          .catch(err => console.error("替换轨道失败:", err));
      }
    });
  });
};

额外注意事项

  • 当PeerConnection断开时,记得从数组中移除对应实例,防止内存泄漏:
// 监听连接状态变化,移除已断开的连接
pc.onconnectionstatechange = () => {
  if (pc.connectionState === "closed" || pc.connectionState === "disconnected") {
    const idx = activePeerConnections.indexOf(pc);
    if (idx !== -1) {
      activePeerConnections.splice(idx, 1);
    }
  }
};
  • 替换轨道前,可先判断PeerConnection的状态是否为connected,避免对未稳定连接的实例执行无效操作。

内容的提问来源于stack exchange,提问作者Ravindu Dharmadasa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:53:22