航线任务
This commit is contained in:
86
src/components/useWebRTCStream.tsx
Normal file
86
src/components/useWebRTCStream.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
declare const JSWebrtc: any;
|
||||
|
||||
// 🔥 修复:url 变成必传,deviceId + url 共同作为唯一标识
|
||||
export function useWebRTCPlayer(deviceId: string, url: string) {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const playerRef = useRef<any>(null);
|
||||
const readyRef = useRef(false);
|
||||
|
||||
const [ready, setReady] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
// 统一销毁
|
||||
const destroyPlayer = () => {
|
||||
if (playerRef.current) {
|
||||
try { playerRef.current.destroy(); } catch { }
|
||||
playerRef.current = null;
|
||||
}
|
||||
if (videoRef.current) {
|
||||
try {
|
||||
videoRef.current.pause();
|
||||
videoRef.current.srcObject = null;
|
||||
} catch { }
|
||||
videoRef.current = null;
|
||||
}
|
||||
readyRef.current = false;
|
||||
setReady(false);
|
||||
setError(false);
|
||||
};
|
||||
|
||||
// 🔥 修复依赖:[deviceId, url]
|
||||
useEffect(() => {
|
||||
if (!deviceId || !url) {
|
||||
destroyPlayer();
|
||||
return;
|
||||
}
|
||||
|
||||
destroyPlayer();
|
||||
|
||||
// 每个 Hook 创建独立 video
|
||||
const v = document.createElement('video');
|
||||
v.autoplay = true;
|
||||
v.muted = true;
|
||||
v.playsInline = true;
|
||||
v.style.width = '100%';
|
||||
v.style.height = '100%';
|
||||
v.style.objectFit = 'contain';
|
||||
videoRef.current = v;
|
||||
|
||||
const token = localStorage.getItem('videotoken') || JSON.parse(localStorage.getItem('userInfo') || '{}')?.token;
|
||||
const videoUrl = `${url}?token=${token}`;
|
||||
|
||||
try {
|
||||
const player = new JSWebrtc.Player(videoUrl, {
|
||||
video: v,
|
||||
autoplay: true,
|
||||
onPlay: () => {
|
||||
setReady(true);
|
||||
setError(false);
|
||||
readyRef.current = true;
|
||||
},
|
||||
onError: (err: any) => {
|
||||
console.error('播放错误', deviceId, url, err);
|
||||
setError(true);
|
||||
setReady(false);
|
||||
},
|
||||
});
|
||||
playerRef.current = player;
|
||||
} catch (e) {
|
||||
console.error('初始化失败', e);
|
||||
setError(true);
|
||||
}
|
||||
|
||||
return () => {
|
||||
destroyPlayer();
|
||||
};
|
||||
}, [deviceId, url]); // 🔥 必须加 url
|
||||
|
||||
return {
|
||||
video: videoRef.current,
|
||||
ready,
|
||||
error,
|
||||
destroyPlayer,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user