Skip to content

Commit 406520b

Browse files
committed
restore settimeout instead of polling
1 parent 6856c02 commit 406520b

File tree

1 file changed

+9
-30
lines changed

1 file changed

+9
-30
lines changed

packages/react/src/lib/useSoundPlayer.ts

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { convertLinearFrequenciesToBark } from './convertFrequencyScale';
55
import { generateEmptyFft } from './generateEmptyFft';
66
import type { AudioOutputMessage } from '../models/messages';
77

8-
const FADE_DURATION = 0.1;
8+
const FADE_DURATION = 0.05;
99
const FADE_TARGET = 0.0001;
1010

1111
export const useSoundPlayer = (props: {
@@ -125,25 +125,7 @@ export const useSoundPlayer = (props: {
125125
[isAudioMuted, volume],
126126
);
127127

128-
const waitForAudioTime = (
129-
targetTime: number,
130-
ctx: AudioContext,
131-
isCancelled: () => boolean,
132-
): Promise<void> =>
133-
new Promise((resolve) => {
134-
const check = () => {
135-
if (isCancelled()) return;
136-
137-
if (ctx.currentTime >= targetTime) {
138-
resolve();
139-
} else {
140-
requestAnimationFrame(check);
141-
}
142-
};
143-
check();
144-
});
145-
146-
const fadeOutAndPostMessage = useCallback((type: 'end' | 'clear') => {
128+
const fadeOutAndPostMessage = useCallback(async (type: 'end' | 'clear') => {
147129
if (!gainNode.current || !audioContext.current) {
148130
workletNode.current?.port.postMessage({ type });
149131
return;
@@ -158,12 +140,9 @@ export const useSoundPlayer = (props: {
158140
now + FADE_DURATION,
159141
);
160142

161-
isFadeCancelled.current = false;
162-
//await waitForAudioTime(
163-
// now + FADE_DURATION,
164-
// audioContext.current,
165-
// () => isFadeCancelled.current,
166-
//);
143+
await new Promise((resolve) => {
144+
setTimeout(resolve, FADE_DURATION * 1000);
145+
});
167146

168147
workletNode.current?.port.postMessage({ type });
169148

@@ -179,7 +158,7 @@ export const useSoundPlayer = (props: {
179158
};
180159
}, []);
181160

182-
const stopAll = useCallback(() => {
161+
const stopAll = useCallback(async () => {
183162
isInitialized.current = false;
184163
isProcessing.current = false;
185164
setIsPlaying(false);
@@ -190,7 +169,7 @@ export const useSoundPlayer = (props: {
190169
window.clearInterval(frequencyDataIntervalId.current);
191170
}
192171

193-
fadeOutAndPostMessage('end');
172+
await fadeOutAndPostMessage('end');
194173

195174
if (analyserNode.current) {
196175
analyserNode.current.disconnect();
@@ -220,8 +199,8 @@ export const useSoundPlayer = (props: {
220199
setFft(generateEmptyFft());
221200
}, [fadeOutAndPostMessage]);
222201

223-
const clearQueue = useCallback(() => {
224-
fadeOutAndPostMessage('clear');
202+
const clearQueue = useCallback(async () => {
203+
await fadeOutAndPostMessage('clear');
225204
isProcessing.current = false;
226205
setIsPlaying(false);
227206
setFft(generateEmptyFft());

0 commit comments

Comments
 (0)