MCPcopy
hub / github.com/joshwcomeau/use-sound / useSound

Function useSound

src/index.ts:7–156  ·  view source on GitHub ↗
(
  src: string | string[],
  {
    id,
    volume = 1,
    playbackRate = 1,
    soundEnabled = true,
    interrupt = false,
    onload,
    ...delegated
  }: HookOptions<T> = {} as HookOptions
)

Source from the content-addressed store, hash-verified

5import { HookOptions, PlayOptions, PlayFunction, ReturnedValue } from './types';
6
7export 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 });

Callers 7

ShowWhilePlayingFunction · 0.85
RisingFunction · 0.85
SimpleFunction · 0.85
MultipleSourcesDemoFunction · 0.85
Checkbox.jsFile · 0.85
HoverFunction · 0.85
DrumMachineFunction · 0.85

Calls 1

useOnMountFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…