audiocn

useAudioContext

One shared AudioContext that resumes on the first user gesture, plus a provider to supply your own.

Browsers only let audio start after the user interacts with the page. Every audiocn Web Audio hook shares one AudioContext, and this hook resumes it on the first click, tap or key press.

$ pnpm dlx shadcn@latest add @audiocn/use-audio-context

Usage

const { context, status, resume } = useAudioContext();

if (status === "suspended") {
  return <Button onClick={resume}>Enable audio</Button>;
}

Your own context

Wrap your app in AudioContextProvider to make every hook use a context you created, for example one with a specific sample rate.

const context = new AudioContext({ sampleRate: 48_000 });

<AudioContextProvider context={context}>
  <App />
</AudioContextProvider>;

Components that only sometimes play, such as a knob's click, read the provided context with useProvidedAudioContext(). It returns null without a provider and never creates the shared context, so a silent component leaves audio alone.

Returns

Prop

Type