Audio player

A player with a playlist you reorder: pick a track, scrub through it, and drag a track to where you want it.

Goal

A music player, a podcast queue or a lesson playlist: the media is one audio element, and the list beside it is data the user edits. The current track keeps playing while the list is reordered, Enter or a click chooses a track, and the whole list works from the keyboard.

Primitives

  • MediaController is the playback core: it loads a track, plays, pauses, seeks and reports one state snapshot, so the player never listens to an audio event. The recipe loads each clip through a Blob with its resolveSource and releaseSource hooks, drives the seek bar with scrub (a debounced seek) and skip, and reads the position every animation frame from onProgress.
  • AudioVisualizerController feeds the cover the sound of the audio element. Both presets draw on a canvas the visualizer adds to the cover: the LED look (variant: 'led', the default) draws 40 bars of 14 segments, the Bars look (variant: 'solid') draws 40 continuous bars with rounded tops, both with peak caps that hold for 450 ms and then fall, and wave draws the waveform edge to edge. setPreset swaps one for another while the track plays. Their colors are theme tokens. The bars follow log-spaced bands from 80 Hz to 2.4 kHz, where the clips have their sound, and shape each level with floorLevel: 0.32 (the clips' noise is a band that is off), range: 0.66 and curve: 1.6, so quiet bands light no segment while peaks reach the top; at rest the LED look shows one dim segment per bar and the solid one a dim hairline, both with no minimum height while playing, so the cover is never empty under reduced motion. The Play click calls resume() on the visualizer, which starts the audio context inside the gesture.
  • formatMediaTime formats the clock and the total, from the media time helpers.
  • SortableController lets a track be dragged, or lifted with Space and moved with the arrows, and announces each step. It never moves a node, so the recipe keeps the order itself.
  • reorder turns the from and to of a change into the new order.
  • RovingController gives the playlist one tab stop and moves it with the arrows. Its getEnabled is false while a track is lifted, so the arrows that steer the lifted track do not also move focus.
  • PlaybackOrder in audio-player.data is the order the player steps through: list order or a shuffle, with a loop mode, over tracks it holds by identity. It is plain TypeScript with an injectable random source, and its unit tests need no browser. In a shuffle, Previous steps back through the tracks played and Next returns to the track it left before drawing a new one; choosing a track by hand or toggling the shuffle forgets those.

The recipe composes the design system, so it follows the selected theme: the seek bar and the volume are rui-slider elements, the LED, Bars and Wave switch is a rui-toolbar of three toggle buttons named LED bars, Solid bars and Waveform to the right of the title, and the transport buttons carry the Radiant button classes (rui-button, rui-button--ghost and --filled, rui-button--square for icon-only). Loop and shuffle are icon buttons in the same row, with no visible text. The component form renders them with the RuiSlider, RuiToolbar and RuiButton helpers. The plain, element and controller forms write the markup by hand, so they use the light-DOM contracts of the slider (see Custom markup on the slider page) and of the toolbar: a rui-slider host holding a root, a track with its fill and one role="slider" thumb, with the position seeded in the track's custom properties, and a rui-toolbar with exclusive-toggles around buttons that carry data-toggle and aria-pressed. The sound itself is one audio element, and the recipe needs no player library.

Left to the recipe: the playlist (the order, which track is current, and PlaybackOrder for what Next, Previous and the end of a track do), going on to the next track when the controller reports ended, mirroring the state into the buttons, the clock and the seek bar, the status messages, the numbering after a reorder, and the aria-valuetext of the two sliders: a rui-slider writes its own, the bare value, whenever it repaints, so ValueText in audio-player.data keeps the player's text on the thumb with a MutationObserver. The controller reads the audio element's own properties, so the recipe never stores whether it is playing: the status of the state says so.

Example

Choose a track with a click or Enter, press Play or Pause, drag the seek bar, change the volume, and switch the cover between LED, Bars and Wave while it plays. Drag a track to a new place, or press Space on it, move it with the arrow keys and press Space to drop it: the track that is playing keeps playing. When a track ends the next one starts, and the last one stops the player unless the loop is on. The loop button cycles off, all and one, and its accessible name is the mode (Loop: off, Loop: all, Loop: one); it carries no aria-pressed, because a pressed state can only say two things. With all the last track wraps to the first when it ends, with one the same track starts again and Next still moves on, and with off the player stops at the end of the playlist with "End of the playlist". The shuffle button is an on and off toggle with the fixed name Shuffle and aria-pressed. While it is on, Next draws from a bag that holds every track once before any repeats and never plays the same track twice in a row, and Previous walks back through the tracks played. Previous restarts the current track when it has played for more than 3 seconds, in the list order and in a shuffle. Turning shuffle off continues in list order from the current track, and reordering the list keeps the bag and the history on the same tracks. Each change is announced through the status line ("Shuffle on", "Loop: all"). Nothing is stored between visits. Each row is described to a screen reader as "Enter plays, Space picks up to reorder". The seek thumb reads as "0:03 of 0:08" and the volume as "80%", not as the raw number of seconds. The four clips are short tones made for this page: scripts/generate-audio-player-assets.mjs renders them with Node alone, and running it again writes the same bytes.

Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.

Morning Light Radiant Demo
0:00
0:08
  1. 1 Morning Light 0:08
  2. 2 Low Tide 0:08
  3. 3 Neon Rain 0:09
  4. 4 Paper Planes 0:07

Pick a track, or drag one to reorder the playlist

import { RadiantElement, bindTo, customElement, onEvent, query, state } from '@ecopages/radiant';
import {
	createAudioVisualizerController,
	createMediaController,
	createRovingController,
	createSortableController,
	type MediaState,
} from '@ecopages/radiant-ui/controllers';
import '@ecopages/radiant-ui/slider';
import '@ecopages/radiant-ui/toolbar';
import type { RuiSliderChangeDetail, RuiSliderElement } from '@ecopages/radiant-ui/slider';
import { formatMediaTime, reorder } from '@ecopages/radiant-ui/helpers';
import {
	PLAYLIST_HINT,
	PlaybackOrder,
	SEEK_KEYS,
	ValueText,
	VOLUME,
	blobUrlOf,
	createVisualizers,
	loopLabel,
	nextLoopMode,
	seekValueText,
	shuffleAnnouncement,
	volumeValueText,
	type LoopMode,
	type VisualizerName,
} from './audio-player.data';

type Track = { element: HTMLElement; src: string; title: string; artist: string; length: string };

/**
 * @remarks
 * The authored rows are read once into `tracks`, which holds the order from then on. The text that follows the
 * player (title, artist, clock, status), the toggle and the seek bar are `@state` fields that `@bindTo` copies onto
 * the authored markup, so the element never writes to those nodes itself.
 *
 * Playback is a `MediaController` and the cover is an `AudioVisualizerController`, both created with the element as
 * their host, so they attach when it connects and are destroyed when it leaves: the element never listens to the
 * `audio` element and runs no animation frame loop. What stays here is the playlist: the order, which track is
 * current, going on to the next one when a track ends, and the buttons.
 */
@customElement('audio-player-element')
export class AudioPlayerElement extends RadiantElement {
	@query({ selector: '[data-audio]' }) private audio!: HTMLAudioElement;
	@query({ selector: '[data-cover]' }) private cover!: HTMLElement;
	@query({ selector: '[data-tracks]' }) private list!: HTMLElement;
	@query({ selector: '[data-seek]' }) private seek!: RuiSliderElement;
	@query({ selector: '[data-seek] [role="slider"]' }) private seekThumb!: HTMLElement;
	@query({ selector: '[data-volume-input] [role="slider"]' }) private volumeThumb!: HTMLElement;
	@query({ selector: '[data-track]', all: true }) private rows!: HTMLElement[];
	@query({ selector: '[data-name]', all: true }) private names!: HTMLElement[];
	@query({ selector: '[data-length]', all: true }) private lengths!: HTMLElement[];
	@query({ selector: '[data-number]', all: true }) private numbers!: HTMLElement[];

	@state
	@bindTo({ selector: '[data-title]', text: true })
	heading = '';

	@state
	@bindTo({ selector: '[data-artist]', text: true })
	artist = '';

	@state
	@bindTo({ selector: '[data-elapsed]', text: true })
	elapsed = '0:00';

	@state
	@bindTo({ selector: '[data-total]', text: true })
	total = '';

	@state
	@bindTo({ selector: '[data-status]', text: true })
	status = PLAYLIST_HINT;

	@state
	@bindTo({ selector: '[data-seek]', bool: 'disabled', invert: true })
	seekable = false;

	@state
	@bindTo({ selector: '[data-playback]', attr: 'aria-pressed', map: (playing) => String(playing) })
	playing = false;

	@state
	@bindTo({ selector: '[data-loop]', attr: 'data-mode' })
	loopMode: LoopMode = 'off';

	@state
	@bindTo({ selector: '[data-loop]', attr: 'aria-label' })
	loopName = loopLabel('off');

	@state
	@bindTo({ selector: '[data-shuffle]', attr: 'aria-pressed', map: (on) => String(on) })
	shuffled = false;

	private tracks: Track[] = [];
	private current!: Track;
	private order!: PlaybackOrder<Track>;
	private readonly presets = createVisualizers();
	private readonly seekText = new ValueText();
	private readonly volumeText = new ValueText();

	private readonly media = createMediaController(this, {
		getMedia: () => this.audio,
		resolveSource: blobUrlOf,
		releaseSource: (url) => URL.revokeObjectURL(url),
		clearSourceOnDestroy: true,
		onState: (state) => this.renderState(state),
		onProgress: (state) => this.renderProgress(state),
		onError: () => (this.status = `Could not load ${this.heading}`),
	});

	private readonly visualizer = createAudioVisualizerController(this, {
		getMedia: () => this.audio,
		getTarget: () => this.cover,
		preset: this.presets.led,
	});

	private readonly roving = createRovingController(this, {
		getItems: () => this.tracks.map((track) => track.element),
		getTarget: () => this.list,
		orientation: 'vertical',
		getEnabled: () => this.sortable.getState() === null,
	});

	private readonly sortable = createSortableController(this, {
		preview: true,
		liftKeys: [' '],
		createPlaceholder: () => document.createElement('li'),
		getContainer: () => this.list,
		getItems: () => this.tracks.map((track) => track.element),
		announce: (message) => (this.status = message),
		onChange: ({ item, from, to }) => {
			this.tracks = reorder(this.tracks, from, to);
			this.order.setItems(this.tracks);
			this.list.append(...this.tracks.map((track) => track.element));
			this.numbers.forEach((number, index) => (number.textContent = String(index + 1)));
			this.roving.focus(item);
		},
	});

	constructor() {
		super();
		this.registerCleanupCallback(() => {
			this.seekText.stop();
			this.volumeText.stop();
		});
	}

	override onConnected(): void {
		this.seekText.watch(this.seekThumb);
		this.volumeText.watch(this.volumeThumb);
		this.volumeText.set(volumeValueText(VOLUME));
		this.tracks = this.rows.map((element, index) => ({
			element,
			src: element.dataset.src!,
			title: this.names[index].textContent!,
			artist: element.dataset.artist!,
			length: this.lengths[index].textContent!,
		}));
		this.order = new PlaybackOrder(this.tracks, this.tracks[0]);
		this.loopMode = 'off';
		this.loopName = loopLabel('off');
		this.shuffled = false;
		this.roving.sync();
		this.media.setVolume(VOLUME);
		this.status = PLAYLIST_HINT;
		this.load(this.tracks[0], false);
	}

	/**
	 * The one place the media state reaches the page. A track that was playing and is now `ended` is the cue for the
	 * order to say what follows: seeking a paused track to its end reports `ended` too, and must not start another
	 * track.
	 */
	private renderState(state: MediaState): void {
		const playing = state.status === 'playing';
		const finished = state.status === 'ended' && this.playing;
		if (playing && !this.playing) this.status = `Playing ${this.heading}`;
		this.playing = playing;
		this.seekable = state.seekable && state.status !== 'error';
		if (Number.isFinite(state.duration)) {
			this.seek.max = state.duration;
			this.total = formatMediaTime(state.duration);
		}
		this.renderSeekText();
		if (finished) {
			const following = this.order.ended();
			if (following === undefined) this.status = 'End of the playlist';
			else if (following === this.current) this.restart(true);
			else this.load(following, true);
		}
	}

	/** The controller reports the pending scrub target as the position, so the thumb and the clock never jump back. */
	private renderProgress(state: MediaState): void {
		this.seek.value = [state.position];
		this.elapsed = formatMediaTime(state.position);
		this.renderSeekText();
	}

	private renderSeekText(): void {
		this.seekText.set(seekValueText(this.elapsed, this.total));
	}

	/** The slider works in seconds and reports `rui-change` only for the reader, never for a position written to it. */
	@onEvent({ selector: '[data-seek]', type: 'rui-change' })
	scrub(event: Event): void {
		this.media.scrub((event as CustomEvent<RuiSliderChangeDetail>).detail.value[0]);
	}

	/**
	 * Delegated in the capture phase, which runs before the slider's own key handler and lets this stop it for the
	 * keys the player moves by whole seconds.
	 */
	@onEvent({ selector: '[data-seek]', type: 'keydown', options: { capture: true } })
	scrubWithKey(event: Event): void {
		const key = event as KeyboardEvent;
		const distance = SEEK_KEYS[key.key];
		if (distance === undefined) return;
		key.preventDefault();
		key.stopPropagation();
		this.media.skip(distance);
	}

	@onEvent({ selector: '[data-volume-input]', type: 'rui-change' })
	setVolume(event: Event): void {
		const level = (event as CustomEvent<RuiSliderChangeDetail>).detail.value[0];
		this.media.setVolume(level);
		this.volumeText.set(volumeValueText(level));
	}

	/**
	 * The toolbar stops a click on a toggle in its own capture handler, so this is delegated in the capture phase on
	 * the element above it. A click on the pressed button is stopped here, which keeps one of the two pressed.
	 */
	@onEvent({ selector: '[data-visualizer]', type: 'click', options: { capture: true } })
	pickVisualizer(event: Event): void {
		const button = (event.target as Element).closest<HTMLElement>('[data-visualizer]')!;
		if (button.getAttribute('aria-pressed') === 'true') event.stopPropagation();
		else this.visualizer.setPreset(this.presets[button.dataset.visualizer as VisualizerName]);
	}

	@onEvent({ selector: '[data-playback]', type: 'click' })
	togglePlayback(): void {
		this.choose(this.current);
	}

	@onEvent({ selector: '[data-previous]', type: 'click' })
	previous(): void {
		const step = this.order.previous(this.media.getState().position);
		if (step.restart) this.restart(false);
		else this.load(step.track, this.keepsPlaying());
	}

	@onEvent({ selector: '[data-next]', type: 'click' })
	next(): void {
		this.load(this.order.next(), this.keepsPlaying());
	}

	@onEvent({ selector: '[data-loop]', type: 'click' })
	cycleLoop(): void {
		this.order.loop = nextLoopMode(this.order.loop);
		this.loopMode = this.order.loop;
		this.loopName = loopLabel(this.order.loop);
		this.status = this.loopName;
	}

	@onEvent({ selector: '[data-shuffle]', type: 'click' })
	toggleShuffle(): void {
		this.order.setShuffle(!this.order.shuffle);
		this.shuffled = this.order.shuffle;
		this.status = shuffleAnnouncement(this.shuffled);
	}

	@onEvent({ selector: '[data-track]', type: 'click' })
	pick(event: Event): void {
		this.choose(this.trackOf(event));
	}

	@onEvent({ selector: '[data-track]', type: 'keydown' })
	pickWithKey(event: Event): void {
		if ((event as KeyboardEvent).key === 'Enter') this.choose(this.trackOf(event));
	}

	private trackOf(event: Event): Track {
		const row = (event.target as Element).closest('[data-track]');
		return this.tracks.find((track) => track.element === row)!;
	}

	private load(track: Track, autoplay: boolean): void {
		this.current = track;
		this.heading = track.title;
		this.artist = track.artist;
		this.elapsed = '0:00';
		this.total = track.length;
		this.seek.value = [0];
		this.tracks.forEach((candidate) => candidate.element.setAttribute('aria-current', String(candidate === track)));
		void this.media.load(track.src, { autoplay });
	}

	/** Plays the current track again from its start, or leaves it paused there. */
	private restart(play: boolean): void {
		this.media.seek(0);
		if (play) void this.media.play();
	}

	/**
	 * A track that is still loading counts as playing, so Next pressed twice while the first one loads keeps the
	 * playlist going.
	 */
	private keepsPlaying(): boolean {
		return ['playing', 'loading'].includes(this.media.getState().status);
	}

	private choose(track: Track): void {
		this.visualizer.resume();
		if (track !== this.current || this.media.getState().status === 'error') {
			this.order.select(track);
			this.load(track, true);
		} else void this.media.toggle();
	}
}

The element finds its parts with @query, and the rows with @query and all: true, which reads the live DOM on every access, so the numbers are still in document order after a reorder. The authored rows are read once into a tracks array of plain objects, so the title, artist and length of a track are never looked up in its row again. The text that follows the player, the toggle and the seek bar are @state fields that @bindTo copies onto the authored markup: setting this.elapsed, this.playing or this.seekable is the whole update. What the element still writes itself is the seek slider's value and max, which @bindTo has no target for, and the aria-valuetext of the two sliders. The observer that keeps it is stopped by a callback registered once in the constructor.

The two controllers are made with createMediaController(this, ...) and createAudioVisualizerController(this, ...), so they attach when the element connects and are destroyed when it leaves. The element listens to no media event and runs no animation frame loop. onState mirrors the status into aria-pressed and the status message, enables the seek bar and starts the next track when the status is ended; onProgress moves the thumb and the clock on every frame while the track plays. The clips are loaded into a Blob through resolveSource and revoked through releaseSource, so seeking works on servers without range support; serve long media with ranges and load its URL directly. A file that cannot be fetched reaches onError, which sets the status to "Could not load" and the track's title, and choosing the track again loads it again.

@onEvent covers the clicks, the Enter key and the two sliders' rui-change events. The seek slider works in seconds and emits rui-change only for the reader, never for the position the player writes to it, so each one goes to scrub: the clock follows the thumb at once and the controller seeks once the slider has been idle for 120 ms. A key handler delegated in the capture phase moves the thumb by whole seconds with skip, because the slider's own step of 0.01 s, which keeps the per-frame position write smooth, is too small for an arrow key. onConnected starts the player again, from the first track and paused, when the element is moved to another parent. Sortable is given liftKeys: [' '] so that Enter is left to choose a track.

The LED, Bars and Wave buttons are a rui-toolbar with exclusive-toggles. The toolbar stops a click on a toggle in its own capture handler, so the element delegates the click in the capture phase from above it and calls setPreset with the bars or the wave preset; a click on the button that is already pressed is stopped there, so one of the two always stays pressed. The cover is an empty element: both presets add their own decorative canvas to it, and the stylesheet gives the cover a height, its rounded corners and overflow: hidden, which clips the wave to them. The loop and shuffle buttons are @state fields (loopMode, loopName, shuffled) bound to the button's data-mode, aria-label and aria-pressed, over a PlaybackOrder built when the element connects. What the Radiant form removes: the mount function and its registration, the cleanup to return and call, and the re-run after a client-side navigation.

Styles

The current track is selected with aria-current, so the stylesheet needs no class the script would have to keep in step. The lifted track leaves the example while it is dragged, so its style selects it by data-track alone. The cover is a rounded box with overflow: hidden and no border, and the canvas the visualizer adds fills it, so the wave runs edge to edge and is clipped by the corners, while the bars keep their own padding through the preset's padding option. The loop button shows the pressed look for all and one through its data-mode, and the icon with the 1 only for one. The stylesheet is the audio-player.css tab in the files above.