Skip to content

Commit

Permalink
feat: 비디오 pin 이후에도 audioContext가 계속해서 돌아가도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
simeunseo committed Dec 2, 2024
1 parent a134689 commit 212fee1
Showing 1 changed file with 50 additions and 2 deletions.
52 changes: 50 additions & 2 deletions apps/web/src/hooks/mediasoup/useAudioLevelDetector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const useAudioLevelDetector = () => {

const audioContextRef = useRef<AudioContext | null>(null);
const audioLevelsRef = useRef<AudioLevelData[]>([]);
const intervalRef = useRef<number>();

const lastActiveTimeRef = useRef<number>(0);
const currentSpeakerRef = useRef<string | null>(null);
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -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);
};
}, []);

Expand Down

0 comments on commit 212fee1

Please sign in to comment.