useAudioPlayer
Playback state for an audio element the hook owns.
$ pnpm dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-player.json$ npx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-player.json$ yarn dlx shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-player.json$ bunx --bun shadcn-svelte@latest add https://juddisjudd.github.io/audiocn-svelte/r/use-audio-player.jsonUsage
<script lang="ts">
import { Button } from "#lib/components/ui/button/index.js";
import { Waveform } from "#lib/components/ui/waveform/index.js";
import { useAudioPlayer } from "#lib/hooks/use-audio-player.svelte.js";
let { peaks }: { peaks: Float32Array | null } = $props();
const player = useAudioPlayer({ src: "/episode.mp3" });
</script>
<Button onclick={player.toggle}>{player.playing ? "Pause" : "Play"}</Button>
<Waveform {peaks} duration={player.duration} time={player.time} onSeekCommit={player.seek} />The hook creates and owns an <audio> element. Pass player.element to useAudioAnalyser or useWebAudioMixer, and player to AudioPlayer.
Call it during component setup. The options can be a getter, such as () => ({ src: track.src }), so the player follows a new track. The state fields are getters, so read them from the returned object, such as player.playing; destructuring them loses updates. The element exists in the browser only, and stays the same for the life of the component.
Options
| Prop | Type | Default |
|---|---|---|
src | string | — |
autoPlay / loop / muted | boolean | false |
volume 0..1. | number | 1 |
playbackRate | number | 1 |
preload | "none" | "metadata" | "auto" | "metadata" |
crossOrigin Needed to analyse audio from another origin. | "anonymous" | "use-credentials" | — |
onPlay / onPause / onEnded | () => void | — |
onError | (error) => void | — |
Returns
| Prop | Type | Default |
|---|---|---|
element Null during server rendering. | HTMLAudioElement | null | — |
status | "idle" | "loading" | "ready" | "playing" | "paused" | "ended" | "error" | — |
playing | boolean | — |
currentTime Updates about four times a second. | number | — |
time The time on every animation frame while playing. | FrameSource<number> | — |
duration / buffered Seconds. | number | — |
volume / muted / playbackRate / loop Current settings. | number | boolean | — |
play / pause / toggle / seek toggle and play return a promise. | () => void | (seconds) => void | — |
setVolume / setMuted / setPlaybackRate / setLoop | (value) => void | — |