Documentation

Install, wrap, play, stop.

The public API stays focused: safe tone playback, frequency sweeps, short noise bursts, pitch helpers, volume control, and analyser output for React applications.

Start

Install the packages.

Install both packages in app projects so React hooks and core helpers resolve explicitly.

package install
pnpm add @webaudio-kit/react @webaudio-kit/core

Copy-paste React starter

Paste this into App.tsx in a React app after installing the packages. The button click is the user gesture that lets the provider create and resume browser audio.

Paste this into App.tsx
import { AudioProvider, useTone } from "@webaudio-kit/react";

function ToneButton() {
  const tone = useTone({
    frequency: 440,
    gain: 0.15,
    type: "sine",
  });

  return (
    <button onClick={() => void tone.play({ durationMs: 600 })}>
      {tone.isPlaying ? "Restart tone" : "Play tone"}
    </button>
  );
}

export function App() {
  return (
    <AudioProvider>
      <ToneButton />
    </AudioProvider>
  );
}

Provider

Put AudioProvider around the part of the app that owns playback controls. The provider creates the audio context only after a hook needs playback, resumes it from user-initiated handlers, and keeps default master gain at 0.2.

provider setup
import { AudioProvider } from "@webaudio-kit/react";

export function Root() {
  return (
    <AudioProvider>
      <AppControls />
    </AudioProvider>
  );
}

Tone hook

useTone returns stable play, stop, and isPlaying controls. A play call creates a fresh oscillator, gain node, and pan node, then cleans them up when stopped.

tone control
const tone = useTone({
  frequency: 440,
  gain: 0.15,
  type: "sine",
  pan: 0,
});

await tone.play({ durationMs: 500 });
tone.stop();

Envelopes

Use envelope on tones, sweeps, and noise bursts to fade generated audio in and out. Attack, decay, and release are milliseconds; sustain is a 0..1 gain multiplier.

soft cue envelope
const sweep = useFrequencySweep({
  from: 440,
  to: 880,
  durationMs: 500,
  gain: 0.12,
  envelope: { attackMs: 10, decayMs: 40, sustain: 0.7, releaseMs: 80 },
});

Sound shaping

Use filter, detuneCents, and voices to make alert cues less thin or harsh without shipping audio files.

warning cue styling
await tone.play({
  frequency: 660,
  durationMs: 220,
  gain: 0.15,
  type: "sawtooth",
  envelope: { attackMs: 8, releaseMs: 55 },
  filter: { frequency: 1800, q: 0.7 },
  voices: { count: 2, spreadCents: 10 },
});

Repeat patterns

Tones, sweeps, and noise bursts accept pattern: { repeat, gapMs } for alert cues. The returned handle stops the whole scheduled pattern, including future voices.

alert cue pattern
const alertTone = useTone();

await alertTone.play({
  frequency: 880,
  durationMs: 120,
  gain: 0.12,
  type: "square",
  envelope: { attackMs: 8, releaseMs: 45 },
  pattern: { repeat: 3, gapMs: 90 },
});

alertTone.stop();

Sweep hook

useFrequencySweep clamps both frequency endpoints and schedules a linear ramp from from to to. Keep sweep controls conservative in demos.

sweep control
const sweep = useFrequencySweep({
  from: 250,
  to: 8000,
  durationMs: 2400,
  gain: 0.12,
});

await sweep.play();
sweep.stop();

Noise hook

useNoise creates short white, pink, or brown noise buffers per play call. Keep burst duration short and default gain conservative.

noise control
const noise = useNoise({
  type: "pink",
  durationMs: 800,
  gain: 0.08,
});

await noise.play();
noise.stop();

Audio test mode

useAudioTestMode runs a short low-gain diagnostic sequence for tone output, stereo pan, sweep scheduling, noise buffers, and analyser routing.

test mode
const testMode = useAudioTestMode();

await testMode.run();
testMode.stop();

React surfaces and helpers

AudioProvider

Creates AudioContext lazily, owns master gain, connects analyser, and exposes audio state to hooks.

useAudioUnlock

Build an explicit Enable Audio control with idle, suspended, running, and failed unlock status labels.

useTone

Plays oscillator cues with gain, pan, waveform, duration, envelope, filter, detune, voice, and repeat controls.

useFrequencySweep

Ramps frequency between two clamped values over a controlled duration.

useNoise

Plays short white, pink, or brown noise buffers through the provider graph.

useAudioTestMode

Runs short low-gain checks for tone, pan, sweep, noise, and analyser routing.

useAnalyser

Returns the analyser node so UI can render waveform or spectrum data.

useVolumeControl

Creates provider-backed range input props with safe bounds and optional persisted volume preference.

WaveformCanvas

Draws provider analyser data with an idle line before playback starts.

SpectrumCanvas

Draws frequency-domain analyser bars for compact spectrum displays.

math helpers
import {
  clampFrequency,
  dbToGain,
  frequencyToNoteName,
  gainToDb,
} from "@webaudio-kit/core";

const frequency = clampFrequency(inputFrequency); // 20..20000 by default
const gain = dbToGain(-14);
const db = gainToDb(0.2);
const note = frequencyToNoteName(440); // A4

Hooks vs Core

Most React screens should start with hooks. When a screen needs custom @webaudio-kit/core playback, use ensureAudioContext() and route into the provider graph.

Scope and limitations

webaudio-kit is intentionally scoped to safe procedural UI audio. It is not a full synthesizer graph, Tone.js competitor, AudioWorklets toolkit, or medical system.

Framework setup

Provider placement changes slightly between Vite React, Next App Router, and plain React. The dedicated comparison page shows where the provider belongs, where Next client boundaries are required, and how browser autoplay rules affect each setup.

Benchmarks

Local benchmarks cover math helpers, playback scheduling, analyser frame work, and React hook overhead. They are telemetry-free trend checks, not cross-device score claims.

API reference

Use the dedicated API page when you need signatures, option tables, return values, and copy-paste examples for every public React and core export.

AI agent brief CLI

@webaudio-kit/cli can generate an AGENTS.md style file for Codex, Claude Code, Gemini CLI, OpenCode, Antigravity, and similar tools. The file points agents to the public docs, npm pages, examples, browser autoplay rules, safe gain defaults, and non-medical scope boundary before they edit app code.

agent brief
pnpm dlx @webaudio-kit/cli agent-brief
pnpm dlx @webaudio-kit/cli agent-brief --target codex --out AGENTS.md

Browser behavior

Autoplay behavior

Browsers may block audio until the user clicks, taps, or presses a key. Call play from a user action and let the provider resume the context there.

AudioProvider state machine
Safety boundary

Keep default volume low, clamp frequencies, and avoid medical or audiology claims unless a separate certified system validates the whole product.

Release history

The website, npm package pages, and GitHub Releases all point back to the same versioned changelog. Use it when you need to verify published exports, package tarballs, or release notes for a specific version.

More docs

The repository also keeps source Markdown docs for API details, safety, browser behavior, deployment, testing, and performance.