Skip to content

Commit

Permalink
feat: 한번 활성화되고 나면 1초 딜레이를 주어 매끄러운 활성 상태 표시
Browse files Browse the repository at this point in the history
  • Loading branch information
simeunseo committed Dec 2, 2024
1 parent fbb89d1 commit 3e8d4ce
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,21 @@ interface AudioLevelData {
const useAudioLevelDetector = () => {
const audioContextRef = useRef<AudioContext | null>(null);
const audioLevelsRef = useRef<AudioLevelData[]>([]);

const lastActiveTimeRef = useRef<number>(0);
const currentSpeakerRef = useRef<string | null>(null);

const [activeSocketId, setActiveSocketId] = useState<string | null>(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;
Expand All @@ -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);
}
}
};

Expand Down

0 comments on commit 3e8d4ce

Please sign in to comment.