import { useEffect, useRef, useState } from 'react'; declare const JSWebrtc: any; // 🔥 修复:url 变成必传,deviceId + url 共同作为唯一标识 export function useWebRTCPlayer(deviceId: string, url: string) { const videoRef = useRef(null); const playerRef = useRef(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 = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY0MDVjNDgwLTAxNDYtNDAwNS1iY2RiLTFhMTM2YzlmYmFiMCJ9.V1GQiLr0xgu9LB59pGyYPFeVJfKwDsUtTacFrQDpXdEvD81uOkJO304tROF5Ewev6eXkZFuunUAEiMLWEfh2_w" //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, }; }