Skip to content

Commit 86eeec4

Browse files
committed
fix: keep audio player pool in provider context
1 parent 697bccb commit 86eeec4

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/components/AudioPlayer/WithAudioPlayback.tsx

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,27 @@
1-
import type { ReactNode } from 'react';
1+
import React, { useContext, useState } from 'react';
22
import { useEffect, useMemo } from 'react';
33
import type { AudioPlayerOptions } from './AudioPlayer';
44
import { AudioPlayerPool } from './AudioPlayerPool';
55
import { audioPlayerNotificationsPluginFactory } from './plugins/AudioPlayerNotificationsPlugin';
66
import { useChatContext, useTranslationContext } from '../../context';
77

8-
const audioPlayers = new AudioPlayerPool();
8+
export type WithAudioPlaybackProps = { children?: React.ReactNode };
99

10-
export type WithAudioPlaybackProps = { children?: ReactNode };
10+
const AudioPlayerContext = React.createContext<{ audioPlayers: AudioPlayerPool | null }>({
11+
audioPlayers: null,
12+
});
1113

1214
export const WithAudioPlayback = ({ children }: WithAudioPlaybackProps) => {
15+
const [audioPlayers] = useState(() => new AudioPlayerPool());
16+
1317
useEffect(
1418
() => () => {
1519
audioPlayers.clear();
1620
},
17-
[],
21+
[audioPlayers],
1822
);
1923

20-
return children;
24+
return <AudioPlayerContext value={{ audioPlayers }}>{children}</AudioPlayerContext>;
2125
};
2226

2327
export type UseAudioPlayerProps = {
@@ -49,10 +53,11 @@ export const useAudioPlayer = ({
4953
}: UseAudioPlayerProps) => {
5054
const { client } = useChatContext();
5155
const { t } = useTranslationContext();
56+
const { audioPlayers } = useContext(AudioPlayerContext);
5257

5358
const audioPlayer = useMemo(
5459
() =>
55-
src
60+
src && audioPlayers
5661
? audioPlayers.getOrAdd({
5762
durationSeconds,
5863
id: makeAudioPlayerId({ requester, src }),
@@ -62,7 +67,7 @@ export const useAudioPlayer = ({
6267
src,
6368
})
6469
: undefined,
65-
[durationSeconds, mimeType, playbackRates, plugins, requester, src],
70+
[audioPlayers, durationSeconds, mimeType, playbackRates, plugins, requester, src],
6671
);
6772

6873
useEffect(() => {

0 commit comments

Comments
 (0)