From 3ac73c8e8181f40752c0119a233b3d1b6f2a48ff Mon Sep 17 00:00:00 2001 From: Martin <901824+martinstark@users.noreply.github.com> Date: Thu, 11 Apr 2024 11:24:51 +0200 Subject: [PATCH] fix: improve audio clean up logic --- .../production-line/use-rtc-connection.ts | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/src/components/production-line/use-rtc-connection.ts b/src/components/production-line/use-rtc-connection.ts index 04fc2438..c98876e6 100644 --- a/src/components/production-line/use-rtc-connection.ts +++ b/src/components/production-line/use-rtc-connection.ts @@ -1,4 +1,11 @@ -import { Dispatch, SetStateAction, useEffect, useState } from "react"; +import { + Dispatch, + SetStateAction, + useCallback, + useEffect, + useRef, + useState, +} from "react"; import { noop } from "../../helpers"; import { API } from "../../api/api.ts"; import { TJoinProductionOptions } from "./types.ts"; @@ -156,18 +163,29 @@ export const useRtcConnection = ({ const [connectionState, setConnectionState] = useState(null); const [audioElements, setAudioElements] = useState([]); + const audioElementsRef = useRef(audioElements); + + // Use a ref to make sure we only clean up + // audio elements once, and not every time + // the array is updated. + useEffect(() => { + audioElementsRef.current = audioElements; + }, [audioElements]); + + const cleanUpAudio = useCallback(() => { + audioElementsRef.current.forEach((el) => { + el.pause(); + // eslint-disable-next-line no-param-reassign + el.srcObject = null; + }); + }, [audioElementsRef]); // Teardown useEffect( () => () => { - audioElements.forEach((el) => { - console.log("Tearing down audio element"); - el.pause(); - // eslint-disable-next-line no-param-reassign - el.srcObject = null; - }); + cleanUpAudio(); }, - [audioElements] + [cleanUpAudio] ); useEffect(() => {