AudioPlayer
An audio player with playlists, looping, buffered progress, volume, playback speed and compact voice bars. Playback state comes from native media events. Exclusive players can pause other opted-in media in the same document.
Import
import { HuiAudioPlayer } from '@nscode/handy-ui'
import type { AudioPlayerExpose, AudioPlayerTrack, AudioPlayerLoop } from '@nscode/handy-ui'
Examples
URL, track object and preload
<script setup lang="ts">
import { HuiAudioPlayer, HuiSpace } from '@nscode/handy-ui'
const preloads = ['none', 'metadata', 'auto'] as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiAudioPlayer src="/media/demo-tone.wav" />
<HuiAudioPlayer
:src="{
src: '/media/demo-tone.wav',
title: 'Sample audio',
subtitle: 'Three-second local audio',
cover: '/media/demo-poster.svg'
}"
/>
<HuiAudioPlayer
v-for="preload in preloads"
:key="preload"
:src="{ src: '/media/demo-tone.wav', title: `preload=${preload}` }"
:preload="preload"
/>
</HuiSpace>
</template>
Playlist, looping, events and methods
none stops at the end of a playlist but advances from intermediate tracks. one repeats the current track. all returns from the last track to the first. Tracks in this example share a local sample file but have independent indices and playback sessions.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiAudioPlayer, HuiButton, HuiCheckbox, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { AudioPlayerExpose, AudioPlayerLoop, AudioPlayerTrack } from '@nscode/handy-ui'
const tracks: AudioPlayerTrack[] = [
{
src: '/media/demo-tone.wav',
title: 'Track one',
subtitle: 'Three-second local sample',
cover: '/media/demo-poster.svg'
},
{
src: '/media/demo-tone.wav',
title: 'Track two',
subtitle: 'Independent position for the same resource'
},
{ src: '/media/demo-tone.wav', title: 'Track three', subtitle: 'Track switching and looping' }
]
const player = ref<AudioPlayerExpose>()
const index = ref(0)
const loop = ref<AudioPlayerLoop>('none')
const disabled = ref(false)
const muted = ref(false)
const autoplay = ref(false)
const showVolume = ref(true)
const showDownload = ref(false)
const speed = ref(true)
const event = ref('Waiting for native media events')
const rates = computed(() => (speed.value ? [0.5, 0.75, 1, 1.25, 1.5, 2] : []))
const loops = ['none', 'one', 'all'].map((value) => ({ label: value, value }))
const report = (name: string, value?: unknown) => {
event.value = value === undefined ? name : `${name}: ${JSON.stringify(value)}`
}
const describeMedia = () => {
const media = player.value?.getMediaElement()
report(
'getMediaElement',
media ? { tag: media.tagName, paused: media.paused, currentTime: media.currentTime } : null
)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSelect v-model="loop" :options="loops" style="width: 140px" aria-label="Loop mode" />
<HuiCheckbox v-model="disabled">disabled</HuiCheckbox>
<HuiCheckbox v-model="muted">muted</HuiCheckbox>
<HuiCheckbox v-model="autoplay">autoplay</HuiCheckbox>
<HuiCheckbox v-model="showVolume">showVolume</HuiCheckbox>
<HuiCheckbox v-model="showDownload">showDownload</HuiCheckbox>
<HuiCheckbox v-model="speed">Speed menu</HuiCheckbox>
</HuiSpace>
<HuiAudioPlayer
ref="player"
v-model:current-index="index"
:src="tracks"
:loop="loop"
:disabled="disabled"
:muted="muted"
:autoplay="autoplay"
:show-volume="showVolume"
:show-download="showDownload"
:playback-rates="rates"
:skip-seconds="10"
@play="report('play')"
@pause="report('pause')"
@ended="report('ended')"
@timeupdate="(current, duration) => report('timeupdate', { current, duration })"
@ratechange="(rate) => report('ratechange', rate)"
@volumechange="(volume, muted) => report('volumechange', { volume, muted })"
@error="(error) => report('error', error?.message)"
/>
<HuiSpace wrap>
<HuiButton class="audio-demo-play" :disabled="disabled" @click="player?.play()"
>play()</HuiButton
>
<HuiButton @click="player?.pause()">pause()</HuiButton>
<HuiButton :disabled="disabled" @click="player?.toggle()">toggle()</HuiButton>
<HuiButton :disabled="disabled" @click="player?.seek(1)">seek(1)</HuiButton>
<HuiButton :disabled="disabled" @click="player?.prev()">prev()</HuiButton>
<HuiButton :disabled="disabled" @click="player?.next()">next()</HuiButton>
<HuiButton @click="describeMedia">getMediaElement()</HuiButton>
</HuiSpace>
<span class="audio-demo-event" role="status">{{ event }};Current index: {{ index }}</span>
<span
>Playback state comes from browser events. Autoplay can be blocked and usually requires
muted.</span
>
</HuiSpace>
</template>
Compact voice bars and exclusive playback
Small players show only play, progress and time. Only opted-in exclusive instances pause one another. A rejected playback request does not pause other media.
<script setup lang="ts">
import { HuiAudioPlayer, HuiSpace } from '@nscode/handy-ui'
const tracks = ['Voice one', 'Voice two', 'Voice three'].map((title) => ({
title,
src: '/media/demo-tone.wav'
}))
</script>
<template>
<HuiSpace direction="vertical" fill
><HuiAudioPlayer
v-for="track in tracks"
:key="track.title"
:src="track"
size="small"
exclusive
:aria-label="track.title"
/></HuiSpace>
</template>
Narrow layout and slots
A default player narrower than 360px keeps play, progress, time and mute, placing other actions in More. Replace cover and title or place an input in extra; typing there does not trigger player shortcuts.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAudioPlayer, HuiButton, HuiIcon, HuiInput, HuiSpace } from '@nscode/handy-ui'
const note = ref('')
const status = ref('Waiting for an action')
const tracks = [
{ src: '/media/demo-tone.wav', title: 'Track one' },
{ src: '/media/demo-tone.wav', title: 'Track two' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiAudioPlayer
:src="tracks"
:skip-seconds="10"
show-download
style="width: 280px; max-width: 100%; flex: none"
/>
<HuiAudioPlayer :src="{ src: '/media/demo-tone.wav', title: 'Custom title' }">
<template #cover><HuiIcon name="play" /></template>
<template #title="{ track }"
><strong>{{ track?.title }}</strong></template
>
<template #extra
><HuiSpace
><HuiInput v-model="note" placeholder="Notes do not trigger media shortcuts" /><HuiButton
@click="status = `Note: ${note}`"
>Record</HuiButton
></HuiSpace
></template
>
</HuiAudioPlayer>
<span role="status">{{ status }}</span>
</HuiSpace>
</template>
Controlled index and parent rejection
Prop presence controls currentIndex, including explicit undefined. Without accepting updates, the parent keeps its track. Omitting the prop enables internal state. Accepted source changes resume only when playback was active before switching.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAudioPlayer, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
const index = ref(0)
const accept = ref(false)
const requested = ref<number>()
const tracks = [
{ src: '/media/demo-tone.wav', title: 'First track' },
{ src: '/media/demo-tone.wav', title: 'Second track' }
]
const update = (next: number) => {
requested.value = next
if (accept.value) index.value = next
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="accept">Accept track requests</HuiCheckbox>
<HuiAudioPlayer :src="tracks" :current-index="index" @update:current-index="update" />
<span>Actual index: {{ index }}; requested index: {{ requested ?? '(empty)' }}</span>
</HuiSpace>
</template>
Muted autoplay, disabled state and cross-origin attributes
Browser policy decides whether autoplay is allowed. NotAllowedError and AbortError do not emit component errors; native events remain the source of truth. These examples use same-origin files. Cross-origin media also needs server CORS configuration.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAudioPlayer, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
const disabled = ref(false)
const origins = ['', 'anonymous', 'use-credentials'] as const
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="disabled">disabled: pause and block playback actions</HuiCheckbox>
<HuiAudioPlayer src="/media/demo-tone.wav" autoplay muted :disabled="disabled" />
<HuiAudioPlayer
v-for="crossorigin in origins"
:key="crossorigin"
:src="{ src: '/media/demo-tone.wav', title: `crossorigin=${crossorigin || '(empty)'}` }"
:crossorigin="crossorigin"
/>
</HuiSpace>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| src | string | AudioPlayerTrack | AudioPlayerTrack[] | — | URL, track or playlist; empty sources disable playback |
| currentIndex | number | Internal 0 when omitted | Zero-based controlled index; out-of-range display clamps to available tracks |
| autoplay | boolean | false | Native autoplay request |
| muted | boolean | false | Native muted property; commonly paired with autoplay |
| loop | AudioPlayerLoop | 'none' | none/one/all |
| preload | 'none' | 'metadata' | 'auto' | 'metadata' | Native preload policy |
| playbackRates | number[] | [0.5, 0.75, 1, 1.25, 1.5, 2] | Empty hides speed; duplicates, nonpositive and nonfinite values are ignored |
| showVolume | boolean | true | Volume in default size; narrow layout shows mute only |
| skipSeconds | number | 0 | Positive finite value enables skip buttons |
| showDownload | boolean | false | Download the current track |
| size | 'default' | 'small' | 'default' | Full player or compact voice bar; does not inherit generic form/global sizes |
| exclusive | boolean | false | Actual playback pauses other exclusive media in the same document |
| disabled | boolean | false | Pause and block play, navigation, seek and volume; pause remains available |
| crossorigin | '' | 'anonymous' | 'use-credentials' | — | Native attribute; server CORS is still required |
Events
| Event | Parameters | Description |
|---|---|---|
| update:currentIndex | index: number | Track request, also emitted without a model binding |
| play | — | Native play event |
| pause | — | Native pause event |
| ended | — | Native ended event, followed by current loop policy |
| timeupdate | currentTime: number, duration: number | Actual time and duration; unknown duration is NaN |
| ratechange | rate: number | Actual playback rate |
| volumechange | volume: number, muted: boolean | Actual volume from 0 to 1 and muted state |
| error | error: MediaError | null | Native media error; progress shows an error and retry action |
Slots
| Slot | Parameters | Description |
|---|---|---|
| cover | { track: AudioPlayerTrack | undefined } | Replace cover |
| title | { track: AudioPlayerTrack | undefined } | Replace title and subtitle area |
| extra | — | Additional content at the right of the header |
Small size hides the header and these slots.
Methods
Use ref<AudioPlayerExpose>().
| Method | Returns | Description |
|---|---|---|
| play() | Promise<void> | Request playback; no-op when disabled, empty or unmounted |
| pause() | void | Pause, including when disabled |
| toggle() | Promise<void> | void | Toggle playback; no-op when disabled |
| seek(seconds) | void | Clamp seconds to duration; unknown duration and invalid values do nothing |
| prev() | void | Request previous track; all-loop can wrap to the end |
| next() | void | Request next track; all-loop can wrap to the start |
| getMediaElement() | HTMLAudioElement | undefined | Native element; undefined during SSR or after unmount |
Types
type AudioPlayerLoop = 'none' | 'one' | 'all'
type AudioPlayerSize = 'default' | 'small'
interface AudioPlayerTrack {
src: string
title?: string
subtitle?: string
cover?: string
}
Also exports AudioPlayerProps, AudioPlayerEmits, AudioPlayerSlots and AudioPlayerExpose.