Skip to content

Commit

Permalink
fix: improve audio clean up logic
Browse files Browse the repository at this point in the history
  • Loading branch information
martinstark committed Apr 15, 2024
1 parent eaef538 commit b3586ad
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions src/components/production-line/use-rtc-connection.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -159,18 +166,29 @@ export const useRtcConnection = ({
const [connectionState, setConnectionState] =
useState<RTCPeerConnectionState | null>(null);
const [audioElements, setAudioElements] = useState<HTMLAudioElement[]>([]);
const audioElementsRef = useRef<HTMLAudioElement[]>(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(() => {
Expand Down

0 comments on commit b3586ad

Please sign in to comment.