Skip to content
Browse documentation

A small lacquered player: the disc turns, the waveform ripples and fills as it plays, and changing track drifts a veil of light across it.

Used forMusic appsPodcastsAudio toolsLanding pages

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/track-player.json

Registered the namespace? Then it’s shadcn add @hairline/track-player. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Music apps

    A now-playing card in a sidebar, a profile or a release page.

  • Podcasts

    An episode player with the waveform to jump to a moment.

  • Audio tools

    Previewing mixes, stems or takes in a studio app.

  • Landing pages

    A playable sample of a product that makes sound.

What it handles for you

A plain audio bar gives no sense of the track, and swapping tracks just changes the text.

Instead of wiring upaudio playermusic player cardnow playing widgetwaveform scrubberpodcast player
  1. Your audio

    A src per track plays through an <audio> element; its own length replaces yours once known.

  2. Scrub the waveform

    Drag along it or use the arrow keys; it carries on from there.

  3. Each track its colour

    The lacquer and the disc follow the track; cover art works too.

  4. A change you can see

    Previous and next drift a veil of light; the track changes under it.

  5. Controlled or not

    Track and playing state, with callbacks for both.

  6. Cheap while playing

    The fill is one clipped layer; the times re-render once a second.

Overview

Music, podcasts, a radio show, a playlist preview: most small players are a grey bar and three icons. Track player is an object with its own finish, a dark lacquer in each track’s colour with a turning disc, the title and three round controls, and a waveform you can drag. While it plays the disc turns, the waveform ripples gently along its length and fills white as the track goes; drag along it, or use the arrow keys, and the fill and the times follow and it carries on from there. Previous and next drift a soft veil of light across the player, and under it the track, its lacquer colour and its disc change over. It plays your audio when a track has a src; without one it keeps its own clock, for previews.

States

play
The disc turns once every 6s; each bar ripples to 72% height and back over 900ms, 55ms apart, so a slow wave runs along it; the fill grows as the track plays.
pause
The disc and the ripple stop where they are; the play and pause icons crossfade.
scrub
The fill and times follow the pointer; letting go seeks there.
change
A veil drifts across over 1.02s in the next track’s colours; at 36% the track, lacquer and disc change over.
end
At the end it stops and goes back to the start.
reduced motion
No ripple, spin or veil.

Usage

usage.tsx
import { TrackPlayer } from "@/components/track-player";<TrackPlayer tracks={[{ id: "1", title: "Altamira Night", artist: "Lumen Vale", duration: 214, src: "/audio/altamira.mp3", tone: "ember" }]} />

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Works with

A playlist with peaks from your server

Work out each track’s peaks once when it’s uploaded and send them with the track; the player draws them as 48 bars.

example.tsx
"use client";import { useState } from "react";import { TrackPlayer, type PlayerTrack } from "@/components/track-player";export function Playlist({ tracks }: { tracks: PlayerTrack[] }) {  const [index, setIndex] = useState(0);  const [playing, setPlaying] = useState(false);  return <TrackPlayer tracks={tracks} index={index} onIndexChange={setIndex} playing={playing} onPlayingChange={setPlaying} label="Playlist" />;}

Props

tracks
{ id, title, artist, duration, src?, peaks?, tone?, output?, art? }[]
Each track: its length in seconds, audio, loudness peaks (any length), lacquer colour, where it plays and cover art.
index / defaultIndex= 0
number
The track on show; controlled or not.
onIndexChange
(index: number) => void
Called under the veil when the track changes.
playing / defaultPlaying= false
boolean
Whether it plays; controlled or not.
onPlayingChange
(playing: boolean) => void
Called on play, pause and at the end.
playingLabel / pausedLabel= "Now playing" / "Paused"
string
Top left.
label= "Player"
string
Names the player for screen readers.

Accessibility and motion

  • Always dark: each track’s lacquer is the card’s own finish, so it reads the same on any page and needs no light version.
  • While playing, one requestAnimationFrame loop reads the audio’s time and writes the fill to a clipped layer; React re-renders only when the whole second changes.
  • The ripple is a CSS animation on each bar paused with the track, so nothing runs while it’s stopped.
  • Without a src it keeps its own clock, so a preview plays with no audio file.
  • The waveform is a slider (arrows ±5s, Page keys ±15s, Home and End); the track title and artist are announced when they change.
  • Reduced motion drops the ripple, the spin and the veil.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Text morph.

Source

"use client";import * as React from "react";import { Pause, Play, SkipBack, SkipForward } from "lucide-react";import { LACQUER, lacquer, mixTone, type LacquerTone } from "./lacquer";import { LightSurface, type LightPaletteName, type LightSurfaceHandle } from "./light-surface";import { TextMorph } from "./text-morph";import { interactionIcon, useInteractionReducedMotion } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * TRACK PLAYER: a small lacquered player for music or a show * *   play     the disc turns, the waveform ripples gently along *            its length and fills white as the track plays *   scrub    drag along the waveform (or use the arrow keys); *            the fill and the times follow, and it carries on *            from there *   change   previous and next drift a soft veil of light across *            the player; under it the track, its lacquer colour *            and its disc change over * * Plays your audio when a track has a src; without one it keeps * its own clock, for previews. An object with its own dark finish: * the same on a light page or a dark one. * * Reduced motion: no ripple, no spin and no veil. * ───────────────────────────────────────────────────────── */export interface PlayerTrack {  id: string;  title: string;  artist: string;  /** Seconds; the audio's own length replaces it once known. */  duration: number;  src?: string;  /** Loudness, 0 to 1 (or 0 to 100), any length; drawn as 48 bars. */  peaks?: number[];  /** This track's lacquer: a named tone or any CSS colour. */  tone?: LacquerTone | (string & {});  /** Top right: where it's playing. */  output?: string;  /** Cover art for the disc; a disc in the track's colour without one. */  art?: string;}export interface TrackPlayerProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "onChange"> {  tracks: PlayerTrack[];  index?: number;  defaultIndex?: number;  onIndexChange?: (index: number) => void;  playing?: boolean;  defaultPlaying?: boolean;  onPlayingChange?: (playing: boolean) => void;  playingLabel?: string;  pausedLabel?: string;  /** Names the player for screen readers. */  label?: string;}const BARS = 48;const VEIL: Record<LacquerTone, LightPaletteName> = { ember: "solar", cobalt: "azure", rose: "prism", emerald: "azure", midnight: "azure", violet: "dusk" };const time = (s: number) => {  const t = Math.max(0, Math.round(s));  return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;};/** Peaks as 48 bar heights; without peaks, a steady made-up shape from the track's id so each track looks its own. */function barsFor(track: PlayerTrack) {  let src = track.peaks;  if (!src?.length) {    let h = 2166136261;    for (const ch of track.id) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);    const rnd = () => ((h = Math.imul(h ^ (h >>> 15), 2246822507)) >>> 0) / 4294967296;    src = Array.from({ length: BARS }, (_, i) => 0.3 + 0.55 * Math.abs(Math.sin(i * 0.42 + rnd() * 2)) * (0.6 + 0.4 * rnd()));  }  const max = Math.max(...src, 1e-6);  return Array.from({ length: BARS }, (_, i) => {    const a = Math.floor((i * src.length) / BARS);    const b = Math.max(a + 1, Math.floor(((i + 1) * src.length) / BARS));    let sum = 0;    for (let j = a; j < b; j++) sum += src[j] ?? 0;    return Math.max(0.16, Math.min(1, sum / (b - a) / max));  });}function Wave({ heights, played, rippling, reduced }: { heights: number[]; played: boolean; rippling: boolean; reduced: boolean }) {  return (    <span className="flex h-full w-full items-center justify-between gap-[2px]">      {heights.map((h, i) => (        <span          key={i}          className="block flex-1 rounded-full"          style={{            height: `${h * 100}%`,            background: played ? "#fff" : "rgb(255 255 255 / 0.28)",            animation: reduced ? undefined : `ui-track-pulse 900ms ease-in-out ${-(i * 55)}ms infinite alternate`,            animationPlayState: rippling ? "running" : "paused",          }}        />      ))}    </span>  );}export function TrackPlayer({  tracks,  index,  defaultIndex = 0,  onIndexChange,  playing,  defaultPlaying = false,  onPlayingChange,  playingLabel = "Now playing",  pausedLabel = "Paused",  label = "Player",  className = "",  style,  ...props}: TrackPlayerProps) {  const reduced = useInteractionReducedMotion();  const surface = React.useRef<LightSurfaceHandle>(null);  const audio = React.useRef<HTMLAudioElement>(null);  const wave = React.useRef<HTMLDivElement>(null);  const playedLayer = React.useRef<HTMLSpanElement>(null);  const [ownIndex, setOwnIndex] = React.useState(defaultIndex);  const [ownPlaying, setOwnPlaying] = React.useState(defaultPlaying);  const at = Math.max(0, Math.min(tracks.length - 1, index ?? ownIndex));  const isPlaying = playing ?? ownPlaying;  const track = tracks[at];  const [known, setKnown] = React.useState<Record<string, number>>({});  const duration = known[track.id] ?? track.duration;  const heights = React.useMemo(() => barsFor(track), [track]);  const [second, setSecond] = React.useState(0);  const [scrubbing, setScrubbing] = React.useState(false);  const clock = React.useRef({ t: 0, second: 0 });  const tone = track.tone ?? "ember";  const setPlaying = (p: boolean) => {    if (playing === undefined) setOwnPlaying(p);    onPlayingChange?.(p);  };  const setIndex = (i: number) => {    if (index === undefined) setOwnIndex(i);    onIndexChange?.(i);  };  /** Writes the fill straight to the clipped layer; the times re-render only when the whole second changes. */  const paint = React.useCallback(    (t: number) => {      clock.current.t = t;      const pct = duration > 0 ? Math.max(0, Math.min(1, t / duration)) : 0;      if (playedLayer.current) playedLayer.current.style.clipPath = `inset(0 ${(100 - pct * 100).toFixed(3)}% 0 0)`;      const s = Math.floor(t);      if (s !== clock.current.second) {        clock.current.second = s;        setSecond(s);      }    },    [duration],  );  React.useLayoutEffect(() => {    paint(clock.current.t);  }, [paint]);  // Playing: the audio's own clock when there is a src, otherwise one of our own.  React.useEffect(() => {    const el = audio.current;    if (track.src && el) {      if (isPlaying) void el.play().catch(() => setPlaying(false));      else el.pause();    }    if (!isPlaying || scrubbing) return;    let raf = 0;    let last = 0;    const tick = (now: number) => {      const dt = last ? (now - last) / 1000 : 0;      last = now;      let t = track.src && el ? el.currentTime : clock.current.t + dt;      if (t >= duration) {        t = 0;        if (el && track.src) el.currentTime = 0;        paint(0);        setPlaying(false);        return;      }      paint(t);      raf = requestAnimationFrame(tick);    };    raf = requestAnimationFrame(tick);    return () => cancelAnimationFrame(raf);    // eslint-disable-next-line react-hooks/exhaustive-deps  }, [isPlaying, scrubbing, track.id, track.src, duration, paint]);  const go = (delta: number) => {    const next = (at + delta + tracks.length) % tracks.length;    const land = () => {      setIndex(next);      clock.current.second = -1;      paint(0);      if (audio.current) audio.current.currentTime = 0;    };    const s = surface.current;    if (!s || reduced) return land();    const t = tracks[next].tone ?? "ember";    s.wave({ direction: "diagonal", palette: t in LACQUER ? VEIL[t as LacquerTone] : "prism", duration: 1020, onMidpoint: land });  };  const seekFrom = (clientX: number) => {    const r = wave.current?.getBoundingClientRect();    if (!r) return;    paint(Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * duration);  };  const commitSeek = () => {    if (audio.current && track.src) audio.current.currentTime = clock.current.t;  };  const disc = track.art    ? undefined    : `conic-gradient(from 40deg, ${mixTone(tone, 1, "#000000")}, ${mixTone(tone, 0.55, "#ffffff")}, ${mixTone(tone, 0.7, "#000000")}, ${mixTone(tone, 0.75, "#ffd36b")}, ${mixTone(tone, 0.6, "#6be4ff")}, ${mixTone(tone, 1, "#000000")})`;  return (    <LightSurface      ref={surface}      direction="diagonal"      veil="#05050a"      role="group"      aria-label={`${label}: ${track.title} by ${track.artist}`}      className={`w-full rounded-[22px] select-none ${className}`}      style={{ ...lacquer(tone), ...style }}      {...props}    >      {track.src && (        <audio          ref={audio}          src={track.src}          preload="metadata"          onLoadedMetadata={(e) => {            const d = e.currentTarget.duration;            if (Number.isFinite(d) && d > 0) setKnown((k) => (k[track.id] === d ? k : { ...k, [track.id]: d }));          }}        />      )}      <div className="@container flex flex-col gap-4 px-5 py-4">        <div className="flex items-center justify-between gap-2 text-[11px] font-medium text-white/75">          <TextMorph>{isPlaying ? playingLabel : pausedLabel}</TextMorph>          {track.output && <span className="truncate font-mono text-[10.5px] text-white/65">{track.output}</span>}        </div>        <div className="flex flex-col items-stretch gap-3 @[18rem]:flex-row @[18rem]:items-center @[18rem]:justify-between @[18rem]:gap-2.5">          <div className="flex min-w-0 items-center gap-3">            <span              aria-hidden              className="relative grid size-11 shrink-0 animate-spin place-items-center overflow-clip rounded-full"              style={{                background: disc,                boxShadow: "inset 0 0 0 1px rgb(255 255 255 / 0.25)",                animationDuration: "6s",                animationPlayState: isPlaying && !reduced ? "running" : "paused",              }}            >              {track.art && <img src={track.art} alt="" className="absolute inset-0 size-full object-cover" />}              <span className="absolute inset-0 rounded-full" style={{ background: "linear-gradient(135deg, rgb(255 255 255 / 0.42) 0%, transparent 45%, rgb(0 0 0 / 0.24) 100%)" }} />              <span className="relative size-3 rounded-full bg-[#0d0707]" style={{ boxShadow: "inset 0 0 0 1px rgb(255 255 255 / 0.35)" }} />            </span>            <div className="min-w-0">              <div className="truncate text-[14.5px] font-semibold leading-snug tracking-[-0.015em] text-white">{track.title}</div>              <div className="truncate text-[12px] text-white/65">{track.artist}</div>            </div>          </div>          <div className="flex shrink-0 items-center justify-center gap-1.5 @[18rem]:justify-end">            <button              type="button"              onClick={() => go(-1)}              aria-label="Previous track"              className="grid size-7 cursor-pointer place-items-center rounded-full bg-white/12 text-white/90 outline-none transition-[background-color,scale] duration-150 hover:bg-white/22 focus-visible:ring-2 focus-visible:ring-white/70 active:scale-[0.92]"            >              <SkipBack className="size-3 fill-current" aria-hidden />            </button>            <button              type="button"              onClick={() => setPlaying(!isPlaying)}              aria-label={isPlaying ? "Pause" : "Play"}              className="grid size-8 cursor-pointer place-items-center rounded-full bg-white text-[#12090a] outline-none transition-[scale] duration-150 focus-visible:ring-2 focus-visible:ring-white/85 active:scale-[0.93]"            >              <span className="grid place-items-center [grid-area:1/1]" style={interactionIcon(isPlaying, reduced)}>                <Pause className="size-3.5 fill-current" aria-hidden />              </span>              <span className="grid place-items-center [grid-area:1/1]" style={interactionIcon(!isPlaying, reduced)}>                <Play className="size-3.5 translate-x-px fill-current" aria-hidden />              </span>            </button>            <button              type="button"              onClick={() => go(1)}              aria-label="Next track"              className="grid size-7 cursor-pointer place-items-center rounded-full bg-white/12 text-white/90 outline-none transition-[background-color,scale] duration-150 hover:bg-white/22 focus-visible:ring-2 focus-visible:ring-white/70 active:scale-[0.92]"            >              <SkipForward className="size-3 fill-current" aria-hidden />            </button>          </div>        </div>        <div>          <div            ref={wave}            role="slider"            tabIndex={0}            aria-label="Position"            aria-valuemin={0}            aria-valuemax={Math.round(duration)}            aria-valuenow={second}            aria-valuetext={`${time(second)} of ${time(duration)}`}            onPointerDown={(e) => {              e.currentTarget.setPointerCapture(e.pointerId);              setScrubbing(true);              seekFrom(e.clientX);            }}            onPointerMove={(e) => scrubbing && seekFrom(e.clientX)}            onPointerUp={() => {              commitSeek();              setScrubbing(false);            }}            onPointerCancel={() => setScrubbing(false)}            onKeyDown={(e) => {              const by = { ArrowRight: 5, ArrowUp: 5, ArrowLeft: -5, ArrowDown: -5, PageUp: 15, PageDown: -15 }[e.key];              const to = by !== undefined ? clock.current.t + by : e.key === "Home" ? 0 : e.key === "End" ? duration - 0.5 : null;              if (to === null) return;              e.preventDefault();              paint(Math.max(0, Math.min(duration, to)));              commitSeek();            }}            className="relative h-9 w-full cursor-pointer touch-none rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-white/60"          >            <Wave heights={heights} played={false} rippling={isPlaying && !scrubbing} reduced={reduced} />            <span ref={playedLayer} aria-hidden className="pointer-events-none absolute inset-0" style={{ clipPath: "inset(0 100% 0 0)" }}>              <Wave heights={heights} played rippling={isPlaying && !scrubbing} reduced={reduced} />            </span>          </div>          <div className="mt-1 flex items-center justify-between font-mono text-[10.5px] tabular-nums text-white/65">            <span>{time(second)}</span>            <span>-{time(Math.max(0, duration - second))}</span>          </div>        </div>      </div>      <span className="sr-only" aria-live="polite">        {`${track.title} by ${track.artist}`}      </span>    </LightSurface>  );}

Registry item: /r/track-player.json