From 3e8d4cef8913330709c8b2f645c255192d8d50b6 Mon Sep 17 00:00:00 2001 From: Eunseo Sim <55528304+simeunseo@users.noreply.github.com> Date: Tue, 3 Dec 2024 03:19:49 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=95=9C=EB=B2=88=20=ED=99=9C=EC=84=B1?= =?UTF-8?q?=ED=99=94=EB=90=98=EA=B3=A0=20=EB=82=98=EB=A9=B4=201=EC=B4=88?= =?UTF-8?q?=20=EB=94=9C=EB=A0=88=EC=9D=B4=EB=A5=BC=20=EC=A3=BC=EC=96=B4=20?= =?UTF-8?q?=EB=A7=A4=EB=81=84=EB=9F=AC=EC=9A=B4=20=ED=99=9C=EC=84=B1=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=20=ED=91=9C=EC=8B=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hooks/mediasoup/useAudioLevelDetector.ts | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts b/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts index 6bd605f2..ffcfd79b 100644 --- a/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts +++ b/apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts @@ -11,16 +11,21 @@ interface AudioLevelData { const useAudioLevelDetector = () => { const audioContextRef = useRef(null); const audioLevelsRef = useRef([]); + + const lastActiveTimeRef = useRef(0); + const currentSpeakerRef = useRef(null); + const [activeSocketId, setActiveSocketId] = useState(null); const startAudioLevelDetection = () => { const AUDIO_THRESHOLD = 0.01; + const SPEECH_END_DELAY = 1000; const detectAudioLevels = () => { const audioLevels = audioLevelsRef.current; let maxLevel = 0; - let currentSpeakerSocketId = null; + let maxLevelSocketId = null; audioLevels.forEach((levelData) => { const { analyser, dataArray, socketId } = levelData; @@ -34,13 +39,27 @@ const useAudioLevelDetector = () => { if (level > maxLevel) { maxLevel = level; - currentSpeakerSocketId = socketId; + maxLevelSocketId = socketId; } }); + if (maxLevel > AUDIO_THRESHOLD) { - setActiveSocketId(currentSpeakerSocketId); + lastActiveTimeRef.current = Date.now(); + + if (currentSpeakerRef.current === null) { + currentSpeakerRef.current = maxLevelSocketId; + setActiveSocketId(maxLevelSocketId); + } else if (maxLevelSocketId !== currentSpeakerRef.current) { + currentSpeakerRef.current = maxLevelSocketId; + setActiveSocketId(maxLevelSocketId); + } } else { - setActiveSocketId(null); + const activeTime = Date.now() - lastActiveTimeRef.current; + + if (activeTime > SPEECH_END_DELAY && currentSpeakerRef.current !== null) { + currentSpeakerRef.current = null; + setActiveSocketId(null); + } } };