+
@@ -544,7 +537,7 @@ export default function DeviceAccessPage() {
-
+
属性
diff --git a/src/components/VolcRtcPlayer.jsx b/src/components/VolcRtcPlayer.jsx
index f9fcc67..235cd85 100644
--- a/src/components/VolcRtcPlayer.jsx
+++ b/src/components/VolcRtcPlayer.jsx
@@ -2,34 +2,70 @@ import React, { useEffect, useRef } from "react";
import { joinRoom, leaveRoom } from "./droneplayer";
import { postLiveHeartbeat } from "@/api/api";
-export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
- console.log(streamData)
+export default function DroneLivePlayer({
+ streamData,
+ videoMode = "NORMAL",
+}) {
const containerRef = useRef(null);
+
+ // 心跳 timer
const timerRef = useRef(null);
- // ------------ 核心修复:防止异步竞态 ------------
- const isBusyRef = useRef(false); // 正在加入/离开,禁止重复操作
- const mountedRef = useRef(true); // 组件是否挂载
+ // 当前 effect 是否有效(防止异步穿透)
+ const aliveRef = useRef(false);
+
+ // 防止 join / leave 并发
+ const busyRef = useRef(false);
useEffect(() => {
- mountedRef.current = true;
const container = containerRef.current;
- // 清空容器,防止 DOM 不为空
- if (container) container.innerHTML = "";
+ // 当前 effect 生效
+ aliveRef.current = true;
- if (!container || !streamData?.url) return;
+ if (!container) return;
+
+ // 强制清空旧 DOM
+ container.innerHTML = "";
+
+ // 没有流地址直接退出
+ if (!streamData?.url) {
+ return;
+ }
+
+ // ---------------- 解析 RTC 参数 ----------------
- // 解析参数
const params = new URLSearchParams(streamData.url);
- const appId = (params.get("app_id") || params.get("appid") || "").trim();
- const roomId = (params.get("room_id") || params.get("roomid") || "").trim();
- const token = decodeURIComponent((params.get("token") || "").trim());
- const userId = (params.get("user_id") || params.get("uid") || "").trim();
- if (!appId || !roomId || !token || !userId) return;
+ const appId = (
+ params.get("app_id") ||
+ params.get("appid") ||
+ ""
+ ).trim();
+
+ const roomId = (
+ params.get("room_id") ||
+ params.get("roomid") ||
+ ""
+ ).trim();
+
+ const token = decodeURIComponent(
+ (params.get("token") || "").trim()
+ );
+
+ const userId = (
+ params.get("user_id") ||
+ params.get("uid") ||
+ ""
+ ).trim();
+
+ if (!appId || !roomId || !token || !userId) {
+ console.error("RTC 参数缺失");
+ return;
+ }
+
+ // ---------------- 心跳 ----------------
- // 心跳
const liveheartbeat = async () => {
try {
await postLiveHeartbeat({
@@ -41,46 +77,89 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
}
};
- // ---------------- 真正安全的初始化流程 ----------------
- const safeInit = async () => {
- // 1. 防止并发:正在忙就直接退出
- if (isBusyRef.current) return;
- isBusyRef.current = true;
+ // ---------------- 初始化 RTC ----------------
+
+ const initRTC = async () => {
+ // 防止重复进入
+ if (busyRef.current) return;
+
+ busyRef.current = true;
try {
- // 2. 【强制顺序】先销毁旧房间 + 清心跳
+ // =========================
+ // 1. 先彻底关闭旧 RTC
+ // =========================
+
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
- leaveRoom(); // 先离开旧房间
- await new Promise((resolve) => setTimeout(resolve, 100));
- // 3. 组件已卸载,直接放弃
- if (!mountedRef.current) {
- isBusyRef.current = false;
+ // 必须 await
+ await leaveRoom();
+
+ // 给 SDK 一点释放时间
+ await new Promise((resolve) =>
+ setTimeout(resolve, 300)
+ );
+
+ // 组件已经卸载
+ if (!aliveRef.current) {
return;
}
- // 4. 加入新房间(此时绝对安全)
- await joinRoom(container, appId, roomId, token, userId, videoMode);
+ // =========================
+ // 2. 加入新房间
+ // =========================
- // 5. 开启心跳
- //timerRef.current = setInterval(liveheartbeat, 3000);
- //liveheartbeat();
+ await joinRoom(
+ container,
+ appId,
+ roomId,
+ token,
+ userId,
+ videoMode
+ );
+
+ // 再次检查
+ if (!aliveRef.current) {
+ await leaveRoom();
+ return;
+ }
+
+ // =========================
+ // 3. 开启心跳
+ // =========================
+
+ /*
+ timerRef.current = setInterval(() => {
+ liveheartbeat();
+ }, 3000);
+
+ liveheartbeat();
+ */
} catch (err) {
- console.error("RTC 初始化失败", err);
+ console.error("RTC 初始化失败:", err);
+
+ // 出错强制释放
+ try {
+ await leaveRoom();
+ } catch (e) {
+ console.error(e);
+ }
} finally {
- // 解锁
- isBusyRef.current = false;
+ busyRef.current = false;
}
};
- safeInit();
+ initRTC();
+
+ // =========================
+ // cleanup
+ // =========================
- // ---------------- 清理函数 ----------------
return () => {
- mountedRef.current = false;
+ aliveRef.current = false;
// 清理心跳
if (timerRef.current) {
@@ -88,8 +167,19 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
timerRef.current = null;
}
- // 离开房间
- leaveRoom();
+ // 异步释放 RTC
+ (async () => {
+ try {
+ await leaveRoom();
+
+ // 清空 DOM
+ if (containerRef.current) {
+ containerRef.current.innerHTML = "";
+ }
+ } catch (err) {
+ console.error("leaveRoom error:", err);
+ }
+ })();
};
}, [
streamData?.url,
@@ -102,7 +192,12 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
);
}
diff --git a/src/components/droneplayer.jsx b/src/components/droneplayer.jsx
index 11b7345..b0dc3f0 100644
--- a/src/components/droneplayer.jsx
+++ b/src/components/droneplayer.jsx
@@ -1,34 +1,159 @@
-import VERTC, { RoomProfileType, StreamIndex } from "@volcengine/rtc";
+import VERTC, {
+ RoomProfileType,
+ StreamIndex,
+} from "@volcengine/rtc";
-let engine;
+let engine = null;
-export async function joinRoom(container, appId, roomId, token, userId) {
- console.info('joinRoom...');
-
- const engine = VERTC.createEngine(appId);
+let currentRemoteUserId = null;
- await engine.joinRoom(token, roomId, { userId }, {
- isAutoPublish: true,
- isAutoSubscribeAudio: true,
- isAutoSubscribeVideo: true,
- roomProfileType: RoomProfileType.meeting,
- });
+let isJoining = false;
- engine.on(VERTC.events.onUserPublishStream, async (e) => {
- if (!container) return;
- // 清空旧内容
- container.innerHTML = '';
+// =========================
+// 创建单例 engine
+// =========================
- await engine.setUserVisibility(false);
- engine.setRemoteVideoPlayer(StreamIndex.STREAM_INDEX_MAIN, {
- userId: e.userId,
- renderDom: container,
- visible: true,
- });
- });
+function getEngine(appId) {
+ if (!engine) {
+ engine = VERTC.createEngine(appId);
+ }
+
+ return engine;
}
+
+// =========================
+// 加入房间
+// =========================
+
+export async function joinRoom(
+ container,
+ appId,
+ roomId,
+ token,
+ userId
+) {
+ if (isJoining) {
+ console.warn("正在 joinRoom,跳过");
+ return;
+ }
+
+ isJoining = true;
+
+ try {
+ console.log("joinRoom start");
+
+ // 先离开旧房间
+ await leaveRoom();
+
+ const rtcEngine = getEngine(appId);
+
+ // 防止重复监听
+ rtcEngine.removeAllListeners();
+
+ // 监听远端流
+ rtcEngine.on(
+ VERTC.events.onUserPublishStream,
+ async (e) => {
+ console.log("收到远端流", e);
+
+ currentRemoteUserId = e.userId;
+
+ if (!container) return;
+
+ try {
+ // 清空旧 video
+ container.innerHTML = "";
+
+ // 隐藏本地
+ await rtcEngine.setUserVisibility(false);
+
+ // 播放远端
+ rtcEngine.setRemoteVideoPlayer(
+ StreamIndex.STREAM_INDEX_MAIN,
+ {
+ userId: e.userId,
+ renderDom: container,
+ visible: true,
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ }
+ }
+ );
+
+ // 加入房间
+ await rtcEngine.joinRoom(
+ token,
+ roomId,
+ { userId },
+ {
+ isAutoPublish: false,
+ isAutoSubscribeAudio: false,
+ isAutoSubscribeVideo: true,
+ roomProfileType:
+ RoomProfileType.meeting,
+ }
+ );
+
+ console.log("joinRoom success");
+ } catch (err) {
+ console.error("joinRoom failed", err);
+ } finally {
+ isJoining = false;
+ }
+}
+
+
+// =========================
+// 离开房间
+// =========================
+
export async function leaveRoom() {
- if (engine) await engine.leaveRoom();
+ if (!engine) {
+ return;
+ }
+
+ console.log("leaveRoom start");
+
+ try {
+ // 移除事件
+ engine.removeAllListeners();
+
+ // 停止远端渲染
+ if (currentRemoteUserId) {
+ try {
+ engine.setRemoteVideoPlayer(
+ StreamIndex.STREAM_INDEX_MAIN,
+ {
+ userId: currentRemoteUserId,
+ renderDom: null,
+ visible: false,
+ }
+ );
+ } catch (e) {
+ console.error(e);
+ }
+ }
+
+ // 离开房间
+ try {
+ await engine.leaveRoom();
+ } catch (e) {
+ console.error(e);
+ }
+
+ // 等待 SDK 内部释放
+ await new Promise((resolve) =>
+ setTimeout(resolve, 500)
+ );
+
+ currentRemoteUserId = null;
+
+ console.log("leaveRoom success");
+ } catch (err) {
+ console.error(err);
+ }
}