Skip to content

Commit

Permalink
feat: add fade in/out
Browse files Browse the repository at this point in the history
  • Loading branch information
remvze committed Feb 11, 2024
1 parent f66a6ff commit 663cb92
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/hooks/use-sound.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo, useEffect, useCallback, useState } from 'react';
import { useMemo, useEffect, useCallback, useState, useRef } from 'react';
import { Howl } from 'howler';

import { useLoadingStore } from '@/store';
Expand All @@ -11,6 +11,7 @@ export function useSound(
const [hasLoaded, setHasLoaded] = useState(false);
const isLoading = useLoadingStore(state => state.loaders[src]);
const setIsLoading = useLoadingStore(state => state.set);
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);

const { isBrowser } = useSSR();
const sound = useMemo<Howl | null>(() => {
Expand Down Expand Up @@ -49,18 +50,35 @@ export function useSound(
}

if (!sound.playing()) {
if (timeout.current) clearTimeout(timeout.current);
sound.volume(0);
sound.fade(
0,
typeof options.volume === 'number' ? options.volume : 0.5,
1000,
);
sound.play();
}
}
}, [src, setIsLoading, sound, hasLoaded, isLoading]);
}, [src, setIsLoading, sound, hasLoaded, isLoading, options.volume]);

const stop = useCallback(() => {
if (sound) sound.stop();
}, [sound]);

const pause = useCallback(() => {
if (sound) sound.pause();
}, [sound]);
if (sound) {
sound.fade(
typeof options.volume === 'number' ? options.volume : 0.5,
0,
1000,
);

timeout.current = setTimeout(() => {
sound.pause();
}, 1000);
}
}, [sound, options.volume]);

const control = useMemo(
() => ({ isLoading, pause, play, stop }),
Expand Down

0 comments on commit 663cb92

Please sign in to comment.