# Tuner

> The note and the pitch of a sound, live from the microphone, with a needle on a scale of cents.

```tsx
import { Tuner } from "@/components/audio-ui/tuner";

/** A chromatic tuner: start it, play or sing a note and read how far from it you are. Nothing is recorded or played back. */
export function TunerDemo() {
  return <Tuner />;
}
```

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

**CLI**

```bash
npx shadcn@latest add @audio-ui/tuner
```

**Manual**

**1. Install the following dependencies:**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/react@0.1.0-beta.14
```

**2. Copy and paste the following code into your project.**

```tsx title="components/audio-ui/tuner.tsx"
import {
  type ChangeEvent,
  useCallback,
  useEffect,
  useRef,
  useState,
} from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  type PitchReading,
  usePitch,
} from "@/hooks/use-pitch";
import { useMicrophone } from "@/hooks/use-microphone";
import { cn } from "@/lib/utils";
import type { Source } from "@/components/audio-ui/primitive";

/** Cents from the note to either end of the gauge: half a semitone, where the next note begins. */
const RANGE_CENTS = 50;
const MARKS = [-50, -25, 0, 25, 50];

interface TunerDisplayProps {
  className?: string;
  /** The live reading, such as `usePitch` returns: `null` while nothing clear is playing. */
  source: Source<PitchReading | null>;
  /** How far from the note still counts as in tune, in cents. @default 5 */
  tolerance?: number;
}

const spoken = (reading: PitchReading, tolerance: number) => {
  const note = `${reading.name.replace("#", " sharp")} ${reading.octave}`;
  const cents = Math.round(reading.cents);
  if (Math.abs(reading.cents) <= tolerance) {
    return `${note}, in tune`;
  }
  return `${note}, ${Math.abs(cents)} cents ${cents > 0 ? "sharp" : "flat"}`;
};

/**
 * The display of a chromatic tuner: the nearest note, a needle on a scale from 50
 * cents flat to 50 sharp, and the frequency. It follows a live `source`
 * frame by frame, written straight into the DOM with no React render, and
 * turns to the primary color, thickens its needle and shows a check when the
 * sound is within `tolerance`: it is never color alone. Exposed as
 * a meter of cents, with the note and how far off it is as its text value.
 */
function TunerDisplay({ className, source, tolerance = 5 }: TunerDisplayProps) {
  const root = useRef<HTMLDivElement>(null);
  const note = useRef<HTMLSpanElement>(null);
  const octave = useRef<HTMLSpanElement>(null);
  const hertz = useRef<HTMLSpanElement>(null);
  const cents = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    const element = root.current;
    const nodes = [note, octave, hertz, cents].map((ref) =>
      ref.current?.appendChild(document.createTextNode(""))
    );
    const [noteNode, octaveNode, hertzNode, centsNode] = nodes;
    if (!(element && noteNode && octaveNode && hertzNode && centsNode)) {
      return;
    }
    let shown: PitchReading | null | undefined;
    const paint = () => {
      const reading = source.getSnapshot();
      if (reading === shown) {
        return;
      }
      shown = reading;
      if (!reading) {
        noteNode.data = "–";
        octaveNode.data = "";
        hertzNode.data = "– Hz";
        centsNode.data = "";
        element.style.setProperty("--tuner-cents", "0");
        element.removeAttribute("data-in-tune");
        element.setAttribute("data-idle", "");
        element.setAttribute("aria-valuenow", "0");
        element.setAttribute("aria-valuetext", "No sound");
        return;
      }
      const offset = Math.round(reading.cents);
      noteNode.data = reading.name.replace("#", "♯");
      octaveNode.data = String(reading.octave);
      hertzNode.data = `${reading.frequency.toFixed(1)} Hz`;
      const inTune = Math.abs(reading.cents) <= tolerance;
      // In tune is never carried by color alone: the needle thickens and a check precedes the offset.
      centsNode.data = `${inTune ? "✓ " : ""}${offset > 0 ? "+" : ""}${offset}¢`;
      element.style.setProperty("--tuner-cents", String(reading.cents));
      element.removeAttribute("data-idle");
      if (inTune) {
        element.setAttribute("data-in-tune", "");
      } else {
        element.removeAttribute("data-in-tune");
      }
      element.setAttribute("aria-valuenow", String(offset));
      element.setAttribute("aria-valuetext", spoken(reading, tolerance));
    };
    paint();
    const unsubscribe = source.subscribe(paint);
    return () => {
      unsubscribe();
      for (const node of nodes) {
        node?.remove();
      }
    };
  }, [source, tolerance]);

  return (
    <div
      aria-label="Tuner"
      aria-valuemax={RANGE_CENTS}
      aria-valuemin={-RANGE_CENTS}
      aria-valuenow={0}
      aria-valuetext="No sound"
      className={cn(
        "group/tuner flex w-full flex-col items-center gap-4 text-center",
        className
      )}
      data-idle=""
      data-slot="tuner"
      ref={root}
      role="meter"
    >
      <div
        aria-hidden="true"
        className="flex items-baseline justify-center font-semibold text-5xl leading-none tabular-nums transition-colors group-data-idle/tuner:text-muted-foreground group-data-in-tune/tuner:text-primary"
      >
        <span ref={note} />
        <span className="text-2xl" ref={octave} />
      </div>
      <div
        aria-hidden="true"
        className="flex w-full max-w-72 items-end gap-2 text-muted-foreground text-sm"
      >
        <span>♭</span>
        <div className="relative h-10 flex-1">
          {MARKS.map((mark) => (
            <span
              className={cn(
                "absolute bottom-0 w-px -translate-x-1/2",
                mark === 0 ? "h-6 bg-foreground" : "h-3 bg-muted-foreground/60"
              )}
              key={mark}
              style={{ left: `${50 + mark}%` }}
            />
          ))}
          <span
            className="absolute bottom-0 h-8 w-0.5 -translate-x-1/2 rounded-full bg-foreground transition-[left,background-color] duration-100 ease-out group-data-idle/tuner:bg-muted-foreground/40 group-data-in-tune/tuner:w-1.5 group-data-in-tune/tuner:bg-primary motion-reduce:transition-none"
            style={{ left: "calc(50% + var(--tuner-cents, 0) * 1%)" }}
          />
        </div>
        <span>♯</span>
      </div>
      <div
        aria-hidden="true"
        className="flex gap-3 text-muted-foreground text-xs tabular-nums"
      >
        <span ref={hertz} />
        <span ref={cents} />
      </div>
    </div>
  );
}

const MIN_REFERENCE = 400;
const MAX_REFERENCE = 480;

interface TunerProps {
  className?: string;
  /** The frequency of A4 in hertz the field starts at: 432 or 442, say. @default 440 */
  reference?: number;
  /** How far from the note still counts as in tune, in cents. @default 5 */
  tolerance?: number;
}

/**
 * A chromatic tuner on its own: the display of the nearest note and how many
 * cents off it is, a button to start the microphone and a field for the pitch
 * of A4. Everything runs in the tab, nothing is recorded or sent. The pieces
 * are `useMicrophone`, `usePitch` and `TunerDisplay`, for a tuner of another
 * shape.
 */
function Tuner({ className, reference = 440, tolerance = 5 }: TunerProps) {
  const microphone = useMicrophone();
  const [a4, setA4] = useState(reference);
  const pitch = usePitch(microphone.analyser, { reference: a4 });
  // A number outside the range, or a field left empty while typing, keeps the last one.
  const changeA4 = useCallback((event: ChangeEvent<HTMLInputElement>) => {
    const next = Number(event.target.value);
    if (next >= MIN_REFERENCE && next <= MAX_REFERENCE) {
      setA4(next);
    }
  }, []);
  return (
    <div
      className={cn(
        "mx-auto flex w-full max-w-72 flex-col items-center gap-4",
        className
      )}
      data-slot="tuner-tool"
    >
      <TunerDisplay source={pitch} tolerance={tolerance} />
      <div className="flex items-center gap-3">
        <Button
          onClick={microphone.isListening ? microphone.stop : microphone.start}
          size="sm"
          type="button"
          variant={microphone.isListening ? "outline" : "default"}
        >
          {microphone.isListening ? "Stop" : "Start"}
        </Button>
        <label
          className="flex items-center gap-1.5 text-muted-foreground text-sm"
          htmlFor="tuner-reference"
        >
          A4
          <Input
            className="h-7 w-16 text-center tabular-nums"
            id="tuner-reference"
            max={MAX_REFERENCE}
            min={MIN_REFERENCE}
            onChange={changeA4}
            step={1}
            type="number"
            value={a4}
          />
          Hz
        </label>
      </div>
      {microphone.error ? (
        <p aria-live="polite" className="text-destructive text-sm">
          {microphone.error}
        </p>
      ) : null}
    </div>
  );
}

export { Tuner, TunerDisplay };
```

**3. Update the import paths to match your project setup.**

**Agent**

Paste this prompt to your agent. It does the rest: it installs the skill, adds the component and wires it to your audio.

```text
Install the audio/ui skill with `npx skills add ouestlabs/audio-ui`, then follow it to add the tuner from audio/ui to my project and wire it to my audio code. Read the docs at https://www.audio-ui.dev/llms.txt first.
```

To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents).

## Usage

```tsx
import { 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.

```tsx
import { 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.

```tsx
const 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`](/docs/engine/analysis#pitch) 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`](/docs/engine/pitch#notes-and-frequencies) 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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `reference` | `number` | `440` | The frequency of A4 in hertz the field starts at, such as 432 or 442. |
| `tolerance` | `number` | `5` | How far from the note still counts as in tune, in cents. |
| `className` | `string` |  | Styles the root. |

### TunerDisplay

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `source` | `Source<PitchReading \| null>` |  | The live reading, such as `usePitch` returns: the note, its octave, the offset in cents and the frequency, or `null` while nothing clear is playing. |
| `tolerance` | `number` | `5` | How far from the note still counts as in tune, in cents. The display turns to the primary color within it. |
| `className` | `string` |  | Styles the root. |

### useMicrophone

Its reference is in [Input](/docs/guides/input#the-microphone).

### usePitch

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `analyser` | `AnalyserNode \| null` |  | The signal to read, with an `fftSize` of at least two periods of `minHz`. |
| `reference` | `number` | `440` | The frequency of A4 in hertz. |
| `minHz` | `number` | `40` | The lowest pitch looked for. |
| `maxHz` | `number` | `2000` | The highest pitch looked for. |
| `minLevel` | `number` | `0.01` | How quiet the signal may be, as an RMS level from 0 to 1, before nothing is detected. |
| `threshold` | `number` | `0.15` | How aperiodic a period may be and still count. Lower is stricter. |
| `median` | `number` | `5` | How many recent detections the reading is the median of: it drops the octave jumps a plucked string starts with. |
| `holdMs` | `number` | `600` | How long the last note stays after the sound stops, so a string's decay does not flicker. |
