useGainNode
A gain node on the shared AudioContext, wired from an input to a destination, with click-free level changes.
The blocks use this hook for every level control and bus: the microphone gain in Mic Setup, the soundboard's master bus, and the output of useSound.
$ pnpm dlx shadcn@latest add @audiocn/use-gain-nodeUsage
import { useGainNode } from "@/hooks/use-gain-node";
import { useMicrophone } from "@/hooks/use-microphone";
import { dbToGain } from "@/lib/audio/decibels";
export const MicMonitor = ({ gainDb }: { gainDb: number }) => {
const microphone = useMicrophone({ enabled: true });
// The microphone, through a gain stage, to the speakers.
useGainNode({ gain: dbToGain(gainDb), input: microphone.stream });
return null;
};Routing
inputtakes aMediaStream, which the hook wraps in a source node, or anyAudioNode. Leave it out to feed the node yourself.destinationis where the node plays. Leave it out for the speakers, passnullto route it yourself, or pass a node such as a mixer input or aMediaStreamAudioDestinationNode.- The hook returns the node, so you can connect more to it, or pass it to
useAudioAnalyserto meter the level after gain.
Levels
gain is linear: use dbToGain from @/lib/audio/decibels for decibels. Changes ramp with a short time constant (timeConstant, default 10 ms), so they never click. A new node starts at its gain instead of ramping up from unity, so a muted node is never heard as it starts.
Each connection lives in an effect and is undone on cleanup. That makes the node safe under StrictMode and <Activity>: hiding disconnects it, and showing reconnects it at the same level.
Prop
Type