From 212fee131cc1a78335c8169e64646b138ea7fb50 Mon Sep 17 00:00:00 2001 From: Eunseo Sim <55528304+simeunseo@users.noreply.github.com> Date: Tue, 3 Dec 2024 04:05:59 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=B9=84=EB=94=94=EC=98=A4=20pin=20?= =?UTF-8?q?=EC=9D=B4=ED=9B=84=EC=97=90=EB=8F=84=20audioContext=EA=B0=80=20?= =?UTF-8?q?=EA=B3=84=EC=86=8D=ED=95=B4=EC=84=9C=20=EB=8F=8C=EC=95=84?= =?UTF-8?q?=EA=B0=80=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hooks/mediasoup/useAudioLevelDetector.ts | 52 ++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts b/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts index ba7289f7..d7c77990 100644 --- a/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts +++ b/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts @@ -15,6 +15,7 @@ const useAudioLevelDetector = () => { const audioContextRef = useRef(null); const audioLevelsRef = useRef([]); + const intervalRef = useRef(); const lastActiveTimeRef = useRef(0); const currentSpeakerRef = useRef(null); @@ -75,10 +76,50 @@ const useAudioLevelDetector = () => { } }; - setInterval(detectAudioLevels, 300); + if (intervalRef.current) { + clearInterval(intervalRef.current); + } + + intervalRef.current = setInterval(detectAudioLevels, 300); + }; + + const resetAudioContext = () => { + if (audioContextRef.current?.state === 'closed') { + audioContextRef.current = new AudioContext(); + + const audioContext = audioContextRef.current; + + audioStreams.forEach((stream) => { + if (stream.kind === 'audio') { + const source = audioContext.createMediaStreamSource(stream.stream); + const analyser = audioContext.createAnalyser(); + analyser.fftSize = 256; + source.connect(analyser); + + const dataArray = new Float32Array(analyser.frequencyBinCount); + + const audioLevelData: AudioLevelData = { + socketId: stream.socketId, + audioLevel: 0, + analyser, + dataArray, + }; + + audioLevelsRef.current = [...audioLevelsRef.current, audioLevelData]; + } + }); + + startAudioLevelDetection(); + } }; const createAudioLevel = (remoteStream: client.RemoteStream) => { + resetAudioContext(); + + if (audioContextRef.current?.state === 'closed') { + audioContextRef.current = null; + } + if (!audioContextRef.current) { audioContextRef.current = new AudioContext(); } @@ -112,9 +153,16 @@ const useAudioLevelDetector = () => { useEffect(() => { return () => { - if (audioContextRef.current) { + if (intervalRef.current) { + clearInterval(intervalRef.current); + } + + if (audioContextRef.current && audioContextRef.current.state !== 'closed') { audioContextRef.current.close(); } + + currentSpeakerRef.current = null; + setActiveSocketId(null); }; }, []);