aiellie

Search

Find a component, template or page

GitHub
Components

Audio Player

A clip that plays where it stands: play and pause, its shape to scrub through, and the time.

0:00 / 0:06
Open full screen
fig. 01 · open it full screen from the corner

Installation

npx shadcn@latest add "@aiellie/audio-player"

shadcn needs the @aiellie registry in components.json first. npx aiellie add audio-player adds it on its first run, then installs the same way.

Audio Player plays a clip where it stands, like a voice note or a spoken reply: a play button that becomes pause, the clip's shape to scrub through, and the time. An audio element underneath does the playing, and the parts read its state.

It's built from parts, so a player without the waveform, or with something else in the middle, is the same pieces arranged differently.

Getting started

  1. Lay out the parts

    peaks is the clip's loudness along its length, each from 0 to 1. Work it out once when the clip is made and keep it with the message.

    components/voice-note.tsx
    import {
      AudioPlayer,
      AudioPlayerButton,
      AudioPlayerTime,
      AudioPlayerWaveform,
    } from "@/components/aiellie/audio-player"
    
    export function VoiceNote({ src, peaks }: { src: string; peaks: number[] }) {
      return (
        <AudioPlayer src={src}>
          <AudioPlayerButton />
          <AudioPlayerWaveform peaks={peaks} />
          <AudioPlayerTime />
        </AudioPlayer>
      )
    }

Anatomy

<div data-slot="audio-player" data-playing>
  <audio />
  <button data-slot="audio-player-button" />
  <div data-slot="audio-player-waveform">
    {/* a bar per peak */}
    <input type="range" /> {/* invisible, over the bars */}
  </div>
  <span data-slot="audio-player-time" />
</div>

Seeking is a range input laid over the bars, so a press lands where it lands and the arrow keys step through the clip.

The time uses tabular figures, so the digits don't shift the row as they tick. A blob URL reports its length late, so pass duration to show it straight away.

Examples

Without the waveform

Leave a part out, or read the state yourself with useAudioPlayer inside the player.

components/voice-note.tsx
<AudioPlayer src={src} className="w-fit">
  <AudioPlayerButton />
  <AudioPlayerTime />
</AudioPlayer>

API reference

AudioPlayer

PropTypeDefaultDescription
srcstringrequiredThe clip.
durationnumberIts length in seconds, shown until the file says.

All other div props are forwarded.

AudioPlayerWaveform

PropTypeDefaultDescription
peaksnumber[]requiredThe loudness along the clip, from 0 to 1.
labelstring"Seek"Names the slider.

useAudioPlayer

FieldTypeDefaultDescription
playingboolean
timenumberSeconds played.
durationnumberSeconds in all.
toggle() => voidPlays or pauses.
seek(fraction: number) => voidJumps to a point, from 0 to 1.

AudioPlayerButton takes the props of TooltipIconButton, and AudioPlayerTime those of a span.