@molecule/app-audio-player-angular
v1.1.0
Published
HTML5 audio player chrome — play/pause, scrub, time, mute toggle, optional visualizer slot
Readme
@molecule/app-audio-player-angular
Angular HTML5 audio player chrome — play/pause, scrub bar, elapsed/total
time, and a mute toggle, over a hidden <audio> element. Use for podcasts,
voice notes, music previews, narrated lessons.
Exports <AudioPlayer> — the Angular counterpart of
@molecule/app-audio-player-react: the same props (React names) and the
same DOM for the same input.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { Component } from '@angular/core'
import { AudioPlayer } from '@molecule/app-audio-player-angular'
@Component({
selector: 'app-player',
standalone: true,
imports: [AudioPlayer],
template: `
<div
mol-audio-player
src="/audio/episode-42.mp3"
title="Episode 42: Getting Started"
subtitle="The Molecule Podcast"
(onPlay)="log('playing')"
(onEnded)="log('finished')"
></div>
`,
})
export class Player {}Type
feature
Installation
npm install @molecule/app-audio-player-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angularAPI
Interfaces
AudioPlayerProps
Props accepted by {@link AudioPlayer} — the same props
@molecule/app-audio-player-react accepts. Node props (title, subtitle,
visualizer) are projected content in Angular (an input cannot carry a
node), so they are typed unknown: pass them in the host template as
[slot=title] / [slot=subtitle] / [slot=visualizer] content, or a plain
string as the input.
interface AudioPlayerProps {
/** Audio source URL (a file, a stream or a data URI). */
src: string
/** Optional title / track name, projected as `[slot=title]` content or a plain string. */
title?: unknown
/** Optional artist / source label, projected as `[slot=subtitle]` content or a plain string. */
subtitle?: unknown
/** Optional waveform / visualizer, projected as `[slot=visualizer]` content. */
visualizer?: unknown
/**
* WebVTT captions file URL. When set, the player loads it on the media
* element's captions `<track>` and shows the current caption under the
* controls, in a polite live region that screen readers announce. Without
* it the track is empty and no caption line is shown.
*/
captions?: string
/** BCP 47 language of the captions (the track's `srclang`). */
captionsLang?: string
/**
* Human-readable name of the captions track. Defaults through i18n
* (`audio.captions`, English "Captions").
*/
captionsLabel?: string
/** Initial muted state. */
defaultMuted?: boolean
/** Autoplay (browser may block). Passed to the `<audio>` element. */
autoPlay?: boolean
/** Called when the media starts playing. */
onPlay?: () => void
/** Called when the media is paused. */
onPause?: () => void
/** Called when the media reaches its end. */
onEnded?: () => void
/** Extra classes on the outer wrapper. */
className?: string
}Classes
AudioPlayer
HTML5 audio player chrome — play/pause, scrub, time, mute, optional visualizer slot.
The host IS the outer <div> (div[mol-audio-player]), matching React's
root exactly, so the wrapper's ClassMap classes are the host's. The
<audio> element, the optional title / subtitle header, the visualizer and
the controls row render inside it, in React's order.
Angular projection needs always-mounted <ng-content> capture points, so
the header (and each of its spans) and the visualizer wrapper live in the
template unconditionally and {@link AudioPlayer.ngDoCheck} reconciles them
against React's DOM — React omits the header when neither title nor subtitle
renders, and renders the visualizer bare, without a wrapper element.
@Component({
selector: 'div[mol-audio-player]',
standalone: true,
imports: [Button, NgTemplateOutlet],
inputs: [
'src',
'title',
'subtitle',
'visualizer',
'captions',
'captionsLang',
'captionsLabel',
'defaultMuted',
'autoPlay',
'onPlay',
'onPause',
'onEnded',
'className',
],
host: {
'[class]': 'classes()',
},
template: `<audio #audio [attr.src]="src" [attr.autoplay]="autoPlay ? '' : null" [muted]="muted" preload="metadata" style="display: none"><track #track kind="captions" [attr.src]="captions" [attr.srclang]="captionsLang" [attr.label]="trackLabel()" /></audio><header #header [class]="stackClasses()"><span #titleSpan [class]="titleClasses()"><ng-content select="[slot=title]"></ng-content>@if (isTemplate(title)) {<ng-container [ngTemplateOutlet]="asTemplate(title)" />}@if (titleText()) {{{ titleText() }}}</span><span #subtitleSpan [class]="subtitleClasses()"><ng-content select="[slot=subtitle]"></ng-content>@if (isTemplate(subtitle)) {<ng-container [ngTemplateOutlet]="asTemplate(subtitle)" />}@if (subtitleText()) {{{ subtitleText() }}}</span></header><span #visualizerSlot><ng-content select="[slot=visualizer]"></ng-content></span>@if (isTemplate(visualizer)) {<ng-container [ngTemplateOutlet]="asTemplate(visualizer)" />}@if (visualizerText()) {{{ visualizerText() }}}<div [class]="controlsClasses()"><button mol-button [variant]="'ghost'" [size]="'sm'" (click)="toggle()" data-mol-id="audio-player-toggle" [attr.aria-label]="toggleLabel()"><span aria-hidden="true">{{ playing ? '⏸' : '▶' }}</span></button><span [class]="timeClasses()" style="min-width: 64px">{{ timeText() }}</span><input type="range" [attr.min]="0" [attr.max]="duration || 0" [attr.step]="0.1" [attr.value]="current" (input)="onSeek($event)" [attr.aria-label]="seekLabel()" data-mol-id="audio-player-seek" [class]="seekClasses()" /><button mol-button [variant]="'ghost'" [size]="'sm'" (click)="toggleMute()" data-mol-id="audio-player-mute" [attr.aria-label]="muteLabel()"><span aria-hidden="true">{{ muted ? '🔇' : '🔊' }}</span></button></div>@if (captions) {<p aria-live="polite" data-mol-id="audio-player-captions" [class]="captionClasses()" style="min-height: 1.5em; white-space: pre-line">{{ caption }}</p>}`,
})
export class AudioPlayer implements OnInit, AfterViewInit, DoCheck, OnChanges, OnDestroy {
src = ''
title?: unknown
subtitle?: unknown
visualizer?: unknown
captions?: string
captionsLang?: string
captionsLabel?: string
defaultMuted?: boolean
autoPlay?: boolean
onPlay?: () => void
onPause?: () => void
onEnded?: () => void
className?: string
@ViewChild('audio') audioRef?: ElementRef<HTMLAudioElement>
@ViewChild('track') trackRef?: ElementRef<HTMLTrackElement>
@ViewChild('header') headerRef?: ElementRef<HTMLElement>
@ViewChild('titleSpan') titleSpanRef?: ElementRef<HTMLElement>
@ViewChild('subtitleSpan') subtitleSpanRef?: ElementRef<HTMLElement>
@ViewChild('visualizerSlot') visualizerSlotRef?: ElementRef<HTMLElement>
playing = false
muted = false
duration = 0
current = 0
caption = ''
private readonly i18n = useTranslation()
private readonly cd = inject(ChangeDetectorRef)
private readonly host: HTMLElement = inject(ElementRef).nativeElement
private readonly renderer = inject(Renderer2)
private readonly slots = new SlotWrapper(inject(ElementRef), this.renderer)
private hasTitleSlot = false
private hasSubtitleSlot = false
private hasVisualizerSlot = false
private visualizerOpen = false
private visualizerChildren: Node[] = []
private detach: Array<() => void> = []
private viewReady = false
private detachCaptions: (() => void) | null = null
cm(): UIClassMap {
return getClassMap()
}
classes(): string {
return this.cm().cn(this.cm().stack(2), this.cm().sp('p', 3), this.className)
}
titleClasses(): string {
return this.cm().cn(this.cm().textSize('sm'), this.cm().fontWeight('semibold'))
}
subtitleClasses(): string {
return this.cm().textSize('xs')
}
captionClasses(): string {
return this.cm().textSize('sm')
}
stackClasses(): string {
return this.cm().cn(this.cm().stack(0))
}
timeClasses(): string {
return this.cm().textSize('xs')
}
seekClasses(): string {
return this.cm().cn(this.cm().flex1)
}
controlsClasses(): string {
return this.cm().flex({ align: 'center', gap: 'sm' })
}
ngOnInit(): void {
this.playing = !!this.autoPlay
this.muted = !!this.defaultMuted
}
ngOnChanges(changes: SimpleChanges): void {
if (!this.viewReady || !('captions' in changes)) return
this.dropCaptions()
this.syncCaptions()
}
ngAfterViewInit(): void {
const audio = this.audioRef?.nativeElement
if (audio) {
const onTimeUpdate = (): void => {
this.current = audio.currentTime
this.cd.markForCheck()
}
const onLoadedMetadata = (): void => {
this.duration = audio.duration
this.cd.markForCheck()
}
const onPlayEvent = (): void => {
this.playing = true
this.onPlay?.()
this.cd.markForCheck()
}
const onPauseEvent = (): void => {
this.playing = false
this.onPause?.()
this.cd.markForCheck()
}
const onEndedEvent = (): void => {
this.playing = false
this.onEnded?.()
this.cd.markForCheck()
}
audio.addEventListener('timeupdate', onTimeUpdate)
audio.addEventListener('loadedmetadata', onLoadedMetadata)
audio.addEventListener('play', onPlayEvent)
audio.addEventListener('pause', onPauseEvent)
audio.addEventListener('ended', onEndedEvent)
this.detach.push(() => {
audio.removeEventListener('timeupdate', onTimeUpdate)
audio.removeEventListener('loadedmetadata', onLoadedMetadata)
audio.removeEventListener('play', onPlayEvent)
audio.removeEventListener('pause', onPauseEvent)
audio.removeEventListener('ended', onEndedEvent)
})
}
this.hasTitleSlot = hasProjectedNodes(this.titleSpanRef?.nativeElement, this.titleText())
this.hasSubtitleSlot = hasProjectedNodes(
this.subtitleSpanRef?.nativeElement,
this.subtitleText(),
)
this.hasVisualizerSlot = hasProjectedNodes(
this.visualizerSlotRef?.nativeElement,
this.visualizerText(),
)
this.viewReady = true
this.syncCaptions()
this.reconcile()
}
ngDoCheck(): void {
this.reconcile()
}
ngOnDestroy(): void {
for (const undo of this.detach.splice(0)) undo()
this.dropCaptions()
}
shows(value: unknown): boolean {
if (isTemplate(value)) return true
return value !== undefined && value !== null && value !== false && value !== '' && value !== 0
}
isTemplate(value: unknown): value is TemplateRef<unknown> {
return isTemplate(value)
}
asTemplate(value: unknown): TemplateRef<unknown> {
return value as TemplateRef<unknown>
}
titleText(): string {
return typeof this.title === 'string' || typeof this.title === 'number'
? String(this.title)
: ''
}
subtitleText(): string {
return typeof this.subtitle === 'string' || typeof this.subtitle === 'number'
? String(this.subtitle)
: ''
}
visualizerText(): string {
return typeof this.visualizer === 'string' || typeof this.visualizer === 'number'
? String(this.visualizer)
: ''
}
timeText(): string {
return `${fmt(this.current)} / ${fmt(this.duration)}`
}
toggleLabel(): string {
return this.playing
? this.i18n.t('audio.pause', {}, { defaultValue: 'Pause' })
: this.i18n.t('audio.play', {}, { defaultValue: 'Play' })
}
muteLabel(): string {
return this.muted
? this.i18n.t('audio.unmute', {}, { defaultValue: 'Unmute' })
: this.i18n.t('audio.mute', {}, { defaultValue: 'Mute' })
}
// … truncated — 10 more members: seekLabel, trackLabel, toggle, onSeek, toggleMute, dropCaptions, syncCaptions, reconcile, syncRange, reconcileVisualizer; the full declaration is in node_modules/@molecule/app-audio-player-angular/dist/audio-player.component.d.ts(Member comments are left out to fit; the full declaration is in node_modules/@molecule/app-audio-player-angular/dist/audio-player.component.d.ts.)
Injection Notes
Requirements
Peer dependencies:
@angular/common^22.0.0@angular/core^22.0.0@angular/platform-browser^22.0.0@molecule/app-angular^3.5.0@molecule/app-ui^1.0.1@molecule/app-ui-angular^1.1.0
Runtime Dependencies
@angular/common@angular/core@angular/platform-browser@molecule/app-angular@molecule/app-ui@molecule/app-ui-angular
There is NO volume slider — only a mute toggle; and no playback-rate
or skip controls. The optional visualizer is projected [slot=visualizer]
content rendered above the controls (bring your own waveform). autoPlay is
passed to the <audio> element and is routinely blocked by browsers until
user interaction — never rely on it. Duration renders 0:00 until
loadedmetadata fires (preload="metadata"). Translations come from the
companion @molecule/app-locales-audio-player locale bond. Node props
(title, subtitle, visualizer) are projected content: [slot=title],
[slot=subtitle], [slot=visualizer].
Translations
Translation strings are provided by @molecule/app-locales-audio-player.
