# Spectrum Analyzer

> The level of a sound across frequencies, live, on a log axis in hertz, with held peaks.

```tsx
import { useCallback, useEffect, useState } from "react";
import { SpectrumAnalyzer } from "@/components/audio-ui/spectrum-analyzer";
import { useSpectrum } from "@/hooks/use-spectrum";
import { useMasterBus } from "@/hooks/use-master-bus";
import { usePlaySwitch } from "@/hooks/use-play-switch";
import { useSynthVoices } from "@/hooks/use-synth-voices";
import { useMidiInput } from "@/hooks/use-midi-input";
import type { EnvelopePoint } from "@/lib/envelope-ramp";
import { webAudio } from "@/lib/web-audio";

const VOLUME = 0.4;
/** A, E, A and E again: a fifth, so the harmonics of the notes meet on the spectrum. */
const CHORD = [45, 52, 57, 64];
/** Held at full level until it is released. */
const ENVELOPE: EnvelopePoint[] = [
  { x: 0, y: 0.05 },
  { x: 0.1, y: 1 },
  { x: 0.9, y: 1 },
  { x: 1, y: 0.05 },
];

/** Press play, in the bar above, or play a MIDI keyboard connected from it, to hold a chord of sawtooth notes and watch the spectrum: each note lights its pitch and every harmonic above it, and the peaks hold a moment after you stop. */
export function SpectrumAnalyzerDemo() {
  const master = useMasterBus(VOLUME);
  const [analyser, setAnalyser] = useState<AnalyserNode | null>(null);
  const { playing } = usePlaySwitch();
  const spectrum = useSpectrum(analyser);
  const { releaseAll, releaseNote, triggerNote } = useSynthVoices({
    destination: master,
    oscillatorType: "sawtooth",
  });

  // The analyzer listens to the master bus, alongside the speakers.
  useEffect(() => {
    const ctx = webAudio.getContext();
    if (!(ctx && master)) {
      return;
    }
    const node = ctx.createAnalyser();
    node.fftSize = 8192;
    node.smoothingTimeConstant = 0.75;
    master.connect(node);
    setAnalyser(node);
    // No disconnect here: the master bus drops all its outputs when it goes, and may already have.
    return () => setAnalyser(null);
  }, [master]);

  useEffect(() => releaseAll, [releaseAll]);

  // The page's play switch, in the preview's bar, holds the chord.
  useEffect(() => {
    if (!playing) {
      return;
    }
    webAudio.resume();
    for (const pitch of CHORD) {
      triggerNote(pitch, ENVELOPE, 0.6);
    }
    return () => {
      for (const pitch of CHORD) {
        releaseNote(pitch, ENVELOPE);
      }
    };
  }, [playing, releaseNote, triggerNote]);

  // A MIDI keyboard, connected from the bar, plays the same voices.
  const noteOn = useCallback(
    (pitch: number, velocity: number) => {
      webAudio.resume();
      triggerNote(pitch, ENVELOPE, velocity);
    },
    [triggerNote]
  );
  const noteOff = useCallback(
    (pitch: number) => releaseNote(pitch, ENVELOPE),
    [releaseNote]
  );
  useMidiInput({ onNoteOff: noteOff, onNoteOn: noteOn });

  return <SpectrumAnalyzer aria-label="Spectrum" source={spectrum} />;
}
```

Shows what a sound is made of: the fundamental and harmonics of a note, the low end of a mix, what an equalizer changes. It is drawn on a `Plot`, so it shares its axes, grid and pointer readout, and follows the audio frame by frame without re-rendering React.

## Installation

**CLI**

```bash
npx shadcn@latest add @audio-ui/spectrum-analyzer
```

**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/spectrum-analyzer.tsx"
import type { ComponentProps } from "react";
import { formatFrequency } from "@/lib/engine/format";
import {
  Plot,
  PlotCursor,
  PlotGraph,
  PlotGrid,
  PlotTrace,
  PlotTraceArea,
} from "@/components/audio-ui/plot";
import { useSpectrumPeaks } from "@/hooks/use-spectrum";
import { cn } from "@/lib/utils";
import type { Source } from "@/components/audio-ui/primitive";

/** Every 20 dB strictly inside the scale, so no label sits on an edge. */
const dbTicks = (min: number, max: number) => {
  const ticks: number[] = [];
  for (let db = Math.floor(min / 20) * 20 + 20; db < max; db += 20) {
    if (db > min) {
      ticks.push(db);
    }
  }
  return ticks;
};
const describePointer = (point: { x: number; y: number }) =>
  `${formatFrequency(point.x)} · ${Math.round(point.y)} dB`;

type SpectrumAnalyzerProps = Omit<
  ComponentProps<typeof Plot>,
  "children" | "maxX" | "maxY" | "minX" | "minY" | "scaleX" | "scaleY"
> & {
  /** The loudest level drawn, in dB. @default -10 */
  maxDb?: number;
  /** Highest frequency on the axis: the same as the spectrum's. @default 20000 */
  maxHz?: number;
  /** The quietest level drawn, in dB. @default -100 */
  minDb?: number;
  /** Lowest frequency on the axis: the same as the spectrum's. @default 20 */
  minHz?: number;
  /** Draws each point's recent peak over the spectrum, held a moment and then falling. @default true */
  peakHold?: boolean;
  /** The peaks to draw, in place of the ones worked out from `source`: your own `useSpectrumPeaks` with another hold or fall, or peaks you compute yourself. */
  peaks?: Source<Float32Array>;
  /** The live spectrum, dB per point along a log frequency axis, such as `useSpectrum` returns. */
  source: Source<Float32Array>;
};

/**
 * A spectrum analyzer: the level of the sound across frequencies, on a log
 * axis in hertz and a scale in dB, with the recent peaks held over it. It
 * follows a live `source` frame by frame without re-rendering React. Point at
 * it to read the frequency and level under the pointer.
 */
function SpectrumAnalyzer({
  className,
  maxDb = -10,
  maxHz = 20_000,
  minDb = -100,
  minHz = 20,
  peakHold = true,
  peaks,
  source,
  ...props
}: SpectrumAnalyzerProps) {
  const held = useSpectrumPeaks(source);
  return (
    <Plot
      className={cn("h-40", className)}
      maxX={maxHz}
      maxY={maxDb}
      minX={minHz}
      minY={minDb}
      scaleX="log"
      {...props}
    >
      <PlotGrid x={{ count: 6 }} y={{ ticks: dbTicks(minDb, maxDb) }} />
      <PlotGraph>
        <PlotTraceArea
          className="fill-primary/20"
          fillTo={minDb}
          source={source}
        />
        <PlotTrace className="stroke-primary/80" source={source} />
        {peakHold ? (
          <PlotTrace className="stroke-foreground/40" source={peaks ?? held} />
        ) : null}
      </PlotGraph>
      <PlotCursor format={describePointer} />
    </Plot>
  );
}

export { SpectrumAnalyzer };
```

**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 spectrum analyzer 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).

## Anatomy

The analyzer is a Plot: a log frequency axis, a filled trace for the spectrum, and a second trace for the peaks.

```tsx
import {
  Plot,
  PlotCursor,
  PlotGraph,
  PlotGrid,
  PlotTrace,
  PlotTraceArea,
} from "@/components/audio-ui/plot";

<Plot scaleX="log">
  <PlotGrid />
  <PlotGraph>
    <PlotTraceArea /> {/* the spectrum, filled */}
    <PlotTrace /> {/* the spectrum's line */}
    <PlotTrace /> {/* the held peaks */}
  </PlotGraph>
  <PlotCursor />
</Plot>
```

## Usage

Tap an `AnalyserNode` anywhere in your graph and turn it into a spectrum with the `use-spectrum` hook:

```tsx
import { SpectrumAnalyzer } from "@/components/audio-ui/spectrum-analyzer";
import { useSpectrum } from "@/hooks/use-spectrum";

const analyser = ctx.createAnalyser();
analyser.fftSize = 8192; // finer low end
output.connect(analyser);

const spectrum = useSpectrum(analyser);

<SpectrumAnalyzer aria-label="Spectrum" source={spectrum} />;
```

Give the analyzer the same `minHz` and `maxHz` as the hook, so each point lands on its frequency. A larger `fftSize` separates low notes better, and `smoothingTimeConstant` sets how fast the spectrum settles.

The peaks come from `useSpectrumPeaks(spectrum, { hold, fall })` in the same hook file: each point keeps its loudest level for `hold` seconds (default 1), then falls at `fall` dB per second (default 24). Both hooks are in [Analysis](/docs/guides/analysis#spectrum).

## API reference

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `source` | `Source<Float32Array>` |  | The live spectrum, dB per point along a log frequency axis, such as `useSpectrum` returns. |
| `minHz` | `number` | `20` | Lowest frequency on the axis: the same as the spectrum's. |
| `maxHz` | `number` | `20000` | Highest frequency on the axis: the same as the spectrum's. |
| `minDb` | `number` | `-100` | The quietest level drawn, in dB. |
| `maxDb` | `number` | `-10` | The loudest level drawn, in dB. |
| `peakHold` | `boolean` | `true` | Draws each point's recent peak over the spectrum, held a moment and then falling. |
| `peaks` | `Source<Float32Array>` |  | The peaks to draw, in place of the ones worked out from `source`: your own `useSpectrumPeaks` with another hold or fall, or peaks you compute yourself. |
| `aria-label` | `string` |  | Names the analyzer. |

Other props go to the `Plot` root, such as `className` for its height.
