From b3586ad78b5ab8aa5648eaa1e596b33a01b6aff7 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 0f69aea7..3600f519 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"; @@ -159,18 +166,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(() => {