Skip to content
ProLifetime access for $199, paid once, every future release included
Truffle UI

Background Music

ProNew

Ambient music for a page: a small floating control with an equalizer that moves only while sound is playing, as a button, a pill or a bar with a track list.

Installation

pnpm dlx shadcn@latest add @viewport/background-music

First time? Add the @viewport registry to components.json. Setup takes one minute.

Usage

The code behind the preview above comes with Truffle Pro.

Props

PropTypeDefault
tracks*AudioTrack[]

What to play. With several tracks the next one starts when one ends.

—
variant"button" | "pill" | "bar"

`button` is a single round play and pause control, `pill` adds the track name and a mute button, `bar` adds previous, next and a pop-up track list.

"pill"
tone"solid" | "glass" | "plain"

`solid` uses the foreground colour, `glass` is a blurred card, `plain` has no background.

"solid"
position"bottom-right" | "bottom-left" | "top-right" | "top-left" | "static"

The corner it floats in. `static` leaves it in the flow of the page.

"bottom-right"
strategy"fixed" | "absolute"

`fixed` pins it to the window, `absolute` to the nearest positioned parent.

"fixed"
autoplayboolean

Start without being asked. Browsers refuse sound before the visitor has interacted with the page, so when the first attempt is refused the music starts on their first click, tap or key press instead.

false
loopboolean

Start over when the last track ends.

true
defaultVolumenumber

Volume at first, from 0 to 1.

0.6
hintstring

Short text shown beside the control until the music first starts.

"Play music"
disabledboolean

Turns the control off.

false
labelstring

Accessible name of the control.

"Background music"
onPlayingChange(playing: boolean) => void

Called when sound starts or stops.

—
classNamestring—

Accessibility

  • Nothing plays before the visitor acts: with autoplay on, a refused start waits for their first click, tap or key press, and the control always shows the real state of the audio element.
  • The main control is a button named Play or Pause background music; mute is a separate button named Mute or Unmute, and the track list is a disclosure that closes on Escape and returns focus to its button.
  • A track that starts is announced politely, and a file that fails to load turns the button into a named Try again control.
  • Under reduced motion the equalizer bars, the ring around the button and the spinner stand still; the bars still change height to show sound is on.