React
@web-kits/audio comes with a set of React hooks to help you use audio in your React applications.
Install Package
Install the package with your package manager of choice.
Add SoundProvider
Wrap your app (or a subtree) with SoundProvider to manage global enabled/volume state. When the user's OS has prefers-reduced-motion: reduce enabled, SoundProvider automatically disables sound.
app.tsx
import { SoundProvider } from "@web-kits/audio/react";
function App() {
const [enabled, setEnabled] = useState(true);
const [volume, setVolume] = useState(0.8);
return (
<SoundProvider
enabled={enabled}
volume={volume}
onEnabledChange={setEnabled}
onVolumeChange={setVolume}
>
{children}
</SoundProvider>
);
}Use Sounds
useSound takes a sound definition and returns a stable play function. The play function returns a VoiceHandle you can use to stop the voice, or undefined when sound is disabled.
button.tsx
import { useSound } from "@web-kits/audio/react";
function SaveButton() {
const play = useSound({
source: { type: "sine", frequency: 880 },
envelope: { decay: 0.1 },
gain: 0.3,
});
return <button onClick={() => play()}>Save</button>;
}