// ~/components/global-audio-player.tsx import { useEffect, useRef } from 'react'; import { useWebRTCStore } from '~/store/webrtc'; export function GlobalWebRTCAudioPlayer() { const audioRef = useRef(null); const remoteStream = useWebRTCStore(state => state.remoteStream); const webRTCStatus = useWebRTCStore(state => state.status); useEffect(() => { const audioElement = audioRef.current; if (audioElement) { if (remoteStream && webRTCStatus === 'CONNECTED') { console.log('GlobalAudioPlayer: Setting remote stream to audio element.'); if (audioElement.srcObject !== remoteStream) { // Avoid unnecessary re-assignments audioElement.srcObject = remoteStream; audioElement.play().catch(error => { // Autoplay policy might prevent play without user interaction. // You might need a UI element for the user to click to start playback. console.warn('GlobalAudioPlayer: Error trying to play audio automatically:', error); // A common pattern is to mute the element initially and then allow unmuting by user action // audioElement.muted = true; // Then provide an unmute button }); } } else { // If stream is null or not connected, clear the srcObject // This also handles the case when leaving a channel. if (audioElement.srcObject) { console.log('GlobalAudioPlayer: Clearing remote stream from audio element.'); audioElement.srcObject = null; } } } }, [remoteStream, webRTCStatus]); // Re-run when remoteStream or connection status changes // This component renders the audio element. // It's generally good practice for