diff --git a/src/hooks/use-sound.ts b/src/hooks/use-sound.ts index eb1e501..6216089 100644 --- a/src/hooks/use-sound.ts +++ b/src/hooks/use-sound.ts @@ -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'; @@ -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 | null>(null); const { isBrowser } = useSSR(); const sound = useMemo(() => { @@ -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 }),