(
src: string | string[],
{
id,
volume = 1,
playbackRate = 1,
soundEnabled = true,
interrupt = false,
onload,
...delegated
}: HookOptions<T> = {} as HookOptions
)
| 5 | import { HookOptions, PlayOptions, PlayFunction, ReturnedValue } from './types'; |
| 6 | |
| 7 | export default function useSound<T = any>( |
| 8 | src: string | string[], |
| 9 | { |
| 10 | id, |
| 11 | volume = 1, |
| 12 | playbackRate = 1, |
| 13 | soundEnabled = true, |
| 14 | interrupt = false, |
| 15 | onload, |
| 16 | ...delegated |
| 17 | }: HookOptions<T> = {} as HookOptions |
| 18 | ) { |
| 19 | const HowlConstructor = React.useRef<HowlStatic | null>(null); |
| 20 | const isMounted = React.useRef(false); |
| 21 | |
| 22 | const [duration, setDuration] = React.useState<number | null>(null); |
| 23 | |
| 24 | const [sound, setSound] = React.useState<Howl | null>(null); |
| 25 | |
| 26 | const handleLoad = function() { |
| 27 | if (typeof onload === 'function') { |
| 28 | // @ts-ignore |
| 29 | onload.call(this); |
| 30 | } |
| 31 | |
| 32 | if (isMounted.current) { |
| 33 | // @ts-ignore |
| 34 | setDuration(this.duration() * 1000); |
| 35 | } |
| 36 | |
| 37 | // @ts-ignore |
| 38 | setSound(this); |
| 39 | }; |
| 40 | |
| 41 | // We want to lazy-load Howler, since sounds can't play on load anyway. |
| 42 | useOnMount(() => { |
| 43 | import('howler').then(mod => { |
| 44 | if (!isMounted.current) { |
| 45 | // Depending on the module system used, `mod` might hold |
| 46 | // the export directly, or it might be under `default`. |
| 47 | HowlConstructor.current = mod.Howl ?? mod.default.Howl; |
| 48 | |
| 49 | isMounted.current = true; |
| 50 | |
| 51 | new HowlConstructor.current({ |
| 52 | src: Array.isArray(src) ? src : [src], |
| 53 | volume, |
| 54 | rate: playbackRate, |
| 55 | onload: handleLoad, |
| 56 | ...delegated, |
| 57 | }); |
| 58 | } |
| 59 | }); |
| 60 | |
| 61 | return () => { |
| 62 | isMounted.current = false; |
| 63 | }; |
| 64 | }); |
no test coverage detected
searching dependent graphs…