Audio UI
Tells you which note a sound is and how far from it you are: tune a guitar, check a vocal, find the key of a sample. The note, the needle and the frequency follow the sound frame by frame without re-rendering React, and everything runs in the tab on the Web Audio API and two audio.js atoms: @audio/pitch-yin finds the pitch, @audio/note names it. Tuner is the whole tool as one element: the display, a start button and a field for the pitch of A4. In tune is within 5 cents.
Installation
Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/tuner
Usage
Copy to Clipboardimport { Tuner } from "@/components/audio-ui/tuner"; <Tuner />;
It asks for the microphone when the start button is pressed: the browser asks for permission then, and a suspended audio context resumes. The microphone is released on stop and when the component unmounts.
In pieces
For a tuner of another shape, three pieces each have one job: useMicrophone gives the signal, usePitch finds its pitch, TunerDisplay shows it.
Copy to Clipboardimport { TunerDisplay } from "@/components/audio-ui/tuner"; import { useMicrophone } from "@/hooks/use-microphone"; import { usePitch } from "@/hooks/use-pitch"; const microphone = useMicrophone(); const pitch = usePitch(microphone.analyser); <button onClick={microphone.start} type="button">Listen</button> <TunerDisplay source={pitch} />;
The signal is raw: echo cancellation, noise suppression and automatic gain are what a call needs, and they flatten the very level a tuner reads. The analyser is never connected to the speakers, so nothing plays back.
Pitch of any signal
usePitch takes any AnalyserNode, not only the microphone's: tap a synth, a track or the master bus and the tuner shows what plays.
Copy to Clipboardconst analyser = ctx.createAnalyser(); analyser.fftSize = 4096; // two periods of the lowest pitch: 4096 at 48 kHz reaches about 40 Hz synth.connect(analyser); const pitch = usePitch(analyser, { minHz: 60, maxHz: 1200, reference: 432 });
The detector is detectPitch of @/lib/engine/analysis, the YIN algorithm of @audio/pitch-yin, for the frequency of an array of samples, and cents(frequency) and midiToHz(note) of @/lib/engine/pitch for the note, its offset in cents and the way back. They are pure functions with no React and no Web Audio, so you can use them off the audio thread, in a test or in any framework.
Accessibility
The display is a meter of cents, from -50 to +50, and its text value reads the note and how far off it is: "A 4, 12 cents flat", "A 4, in tune", "No sound". The display itself is hidden from assistive technology, so a screen reader does not read a new figure twenty times a second.
API reference
Tuner
Props · 3
TunerDisplay
Props · 3
usePitch returns: the note, its octave, the offset in cents and the frequency, or null while nothing clear is playing.useMicrophone
Its reference is in Input.
usePitch
Props · 8
fftSize of at least two periods of minHz.