# visualizer

The sound of a page player made visible: live bars, a wave, a ring or a waveform.

bars draws the spectrum on a log scale from 40 Hz to 16 kHz with a soft fall, wave the oscilloscope as a ribbon, ring the bars around a circle. peaks draws the waveform of the whole track from precomputed peaks, the played part in accent; a click or a drag seeks and hover shows the position. The <audio controls> stays the DOM: native controls, keyboard and media keys.

Module `audio`, category Sound. Import `@dioramajs/audio/visualizer`. [Source](https://github.com/MasterKurosava/diorama/blob/main/packages/audio/src/visualizer.ts)

A player for a short electronic track with live spectrum bars that rise and fall with the music.

```html title="index.html"
<div class="vz-player">
  <div class="vz-head">
    <p class="vz-title">Kite Frequency <span>Sundown warm-up, a 20 s excerpt</span></p>
    <audio src="/media/audio/kite-frequency.mp3" controls preload="metadata">
      <track kind="captions" src="/media/audio/kite-frequency.vtt" srclang="en" label="English" />
    </audio>
  </div>
  <div class="vz-bars" data-dio="visualizer" data-dio-peaks="/media/audio/kite-frequency.json" aria-hidden="true"></div>
</div>
```

## Usage

Put it on: an empty decorative element next to an <audio> or <video>.

`start()` registers `visualizer`, so the attribute alone puts it on an element.

```html
<audio id="live" src="/audio/live-set.mp3" controls="" preload="metadata"></audio><div class="bars" data-dio="visualizer" data-dio-for="#live" aria-hidden="true"></div>
```

In page transitions: Fades with the page transition.

## Params

| Name | Attribute | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `for` (rebuilds) | `data-dio-for` | `string` | `''` | Selector of the audio or video; empty takes the closest one before it. |
| `style` (rebuilds) | `data-dio-style` | `'bars' \| 'wave' \| 'ring' \| 'peaks'` | `'bars'` | bars, wave, ring, or peaks for a waveform of the whole track. |
| `peaks` (rebuilds) | `data-dio-peaks` | `string` | `''` | URL of the peaks JSON: audiowaveform v2 or an array of 0..1. |
| `bars` | `data-dio-bars` | `number` 8 to 128 | `48` | Number of bars. At most low 24. |
| `color` | `data-dio-color` | `color` | `'#ffffff'` | Color of the bars, the wave and the unplayed part. |
| `accent` | `data-dio-accent` | `color` | `'#ff5a36'` | Color of the played part and the position mark. |
| `gap` | `data-dio-gap` | `number` 0 to 0.9 | `0.3` | Gap between bars as a share of a step. |
| `radius` | `data-dio-radius` | `number` 0 to 16 px | `2` | Corner radius of the bars. |
| `range` | `data-dio-range` | `[number, number]` -120 to 0 | `[-90, -20]` | Analyzer range in decibels. |
| `smooth` | `data-dio-smooth` | `number` 0 to 0.99 | `0.75` | Smoothing of the analyzer over time. |
| `mirror` | `data-dio-mirror` | `boolean` | `false` | Bars grow both ways from the middle. |
| `seek` | `data-dio-seek` | `boolean` | `true` | With peaks, a click, a tap or a drag seeks and hover shows the position; off, the waveform only shows progress, for a list where a click opens the episode. |
| `fps` | `data-dio-fps` | `number` 1 to 60 | `30` | Frame cap while playing. At most low 20, medium 30. |

Changing a param marked rebuilds re-runs the effect setup.

### Variants

- `style`: `bars`, `wave`, `ring`, `peaks`

## Inputs and frames

Reads [`delta`](/docs/api/inputs#input-delta), [`reducedMotion`](/docs/api/inputs#input-reducedMotion), [`size`](/docs/api/inputs#size). Draws at a steady rate while it is on screen and stops when it leaves. None while paused; at most fps while playing, then a 0.3 s fall. See [how a frame is decided](/docs/concepts/frames).

## Reduced motion and touch

With reduced motion it shows a still frame: motion inputs are zero and time stands still. bars, wave and ring hold a calm still shape; peaks works fully.

Runs on every device. A tap on peaks seeks; dragging needs touch-action: pan-y.

```ts
import { start } from '@dioramajs/diorama'

start({ effects: { visualizer: { reducedMotion: 'off' } } })
```

## Cost and quality

Loads 5.4 KB the first time a page uses it. GPU: One quad drawn by a fragment shader and a 128 x 1 data texture updated per frame. Memory: A few kilobytes of analyzer data and peaks.

- low: At most 20 fps and 24 bars.
- medium: At most 30 fps.

See [the quality plugin](/docs/effects/quality).

## Recipes

### A podcast episode with a waveform

The `peaks` style draws the whole episode from a small JSON file and shows the played part in `accent`. A click, a tap or a drag along it seeks, so it doubles as a scrubber, and it needs no access to the sound itself. Make the file once per episode with [audiowaveform](https://github.com/bbc/audiowaveform): `audiowaveform -i ep2.mp3 -o ep2.json -z 256 -b 8`.

A podcast episode card with a native player and a waveform that seeks on click.

```html title="index.html"
<article class="vz-episode">
  <p class="vz-ep-show">Signal Notes, episode 2</p>
  <p class="vz-ep-title">The Eagle has landed</p>
  <p class="vz-ep-about">Six seconds of radio that ended thirteen minutes of silence in Houston.</p>
  <audio src="/media/audio/eagle-has-landed.mp3" controls preload="metadata" aria-label="Episode 2, The Eagle has landed">
    <track kind="captions" src="/media/audio/eagle-has-landed.vtt" srclang="en" label="English" />
  </audio>
  <div class="vz-wave" data-dio="visualizer" data-dio-style="peaks" data-dio-peaks="/media/audio/eagle-has-landed.json" data-dio-color="#3a5a8f" data-dio-accent="#7fd3ff" data-dio-gap="0.4" aria-hidden="true" style="touch-action: pan-y"></div>
</article>
```

```ts title="script.ts"
// One player at a time: playing this episode pauses the other examples, and leaving the page
// stops it.
export default function mount(example: HTMLElement): () => void {
  const audio = example.querySelector('audio')
  if (!audio) return () => {}
  const solo = () => {
    for (const other of document.querySelectorAll('doc-example audio'))
      if (other !== audio) (other as HTMLAudioElement).pause()
  }
  audio.addEventListener('play', solo)
  return () => {
    audio.pause()
    audio.removeEventListener('play', solo)
  }
}
```

`touch-action: pan-y` on the waveform lets a finger drag along it while vertical swipes still scroll the page.

### A radio player with a ring

The `ring` style puts the bars around a circle, which frames a round play button or a cover. The `<audio>` can drop its native controls when your own button plays and pauses it.

A round play button inside a ring of bars that pulse with the music.

```html title="index.html"
<div class="vz-radio">
  <audio src="/media/audio/kite-frequency.mp3" preload="metadata">
    <track kind="captions" src="/media/audio/kite-frequency.vtt" srclang="en" label="English" />
  </audio>
  <div class="vz-ring" data-dio="visualizer" data-dio-style="ring" data-dio-bars="96" data-dio-color="#7fd3ff" data-dio-gap="0.4" aria-hidden="true"></div>
  <button type="button" class="vz-play" aria-label="Play Kite Frequency">Play</button>
  <p class="vz-now">Signal Radio <span>Kite Frequency, sundown warm-up</span></p>
</div>
```

```ts title="script.ts"
import { player } from '../_player.ts'

// The round button in the middle of the ring is the player's only control.
export default function mount(example: HTMLElement): () => void {
  return player(
    example,
    example.querySelector<HTMLButtonElement>('.vz-play'),
  )
}
```

### Audio from a CDN

The bars, the wave and the ring read the sound through Web Audio, and the browser lets a page read only sound it is allowed to. For a file on another origin, add `crossorigin="anonymous"` to the element and serve the file with an `Access-Control-Allow-Origin` header that allows your site.

```html
<audio
  id="set"
  src="https://cdn.example.org/sets/sundown.mp3"
  crossorigin="anonymous"
  controls
  preload="metadata"
></audio>
<div
  class="bars"
  data-dio="visualizer"
  data-dio-for="#set"
  aria-hidden="true"
></div>
```

Without both, the effect fails with [`EFFECT_CORS`](/docs/errors/effect-cors) and leaves the element alone, because Web Audio would play an opaque source as silence. The sound keeps playing. The `peaks` style draws from the JSON file and works with any source.

### A list of episodes

In a list where a click on the card opens the episode page, turn `seek` off: the waveform still shows how much has been played, and clicks reach the link.

```html
<li class="episode">
  <a href="/episodes/2">The Eagle has landed</a>
  <audio src="/audio/ep2.mp3" preload="none"></audio>
  <div
    data-dio="visualizer"
    data-dio-style="peaks"
    data-dio-peaks="/peaks/ep2.json"
    data-dio-seek="false"
    aria-hidden="true"
  ></div>
</li>
```

## Notes

The `<audio>` or `<video>` stays the player: its controls, keyboard and media keys work as usual, and the visualizer is decoration with `aria-hidden`. With `for` left empty it takes the closest `<audio>` or `<video>` before it in the same parent, so a player and its bars can sit side by side without an id.

The first play routes the element’s sound through the page’s `AudioContext` for the rest of the element’s life, as browsers allow one such connection per element.

It draws nothing while paused. While playing it draws at most `fps` frames a second, then the bars fall for 0.3 s and it stops. Under reduced motion the bars, the wave and the ring hold a calm still shape, and `peaks` works fully.

`style`, `peaks` and `for` rebuild the effect when they change. Colors, the bar count, the gap and the analyzer range change live.

## Related

- [beat](/docs/effects/beat.md): A cover, logo, card or play button that pulses with the music of a page player: it scales, shakes and glows, or sends out rings, on the beat.
- [vinyl](/docs/effects/vinyl.md): An album cover becomes a record sleeve: the disc slides out and spins.
- [Reduced motion](/docs/guides/reduced-motion.md)
- [Performance and quality](/docs/guides/performance.md)
