API Methods Reference
All public methods on NMMusicPlayer<T>.
Methods follow the overloaded getter/setter pattern: method() reads, method(value) writes.
Factory
nmMPlayer(id?)
nmMPlayer(id?: string | number): NMMusicPlayer<MusicPlaylistItem>
nmMPlayer<T extends MusicPlaylistItem>(id?: string | number): NMMusicPlayer<T>
Creates or retrieves a named player instance.
idis optional. When omitted, the core generates a unique id.- Two calls with the same
idreturn the same instance, no re-initialization. - The factory is the only entry point. Do not call
new NMMusicPlayer()directly. - Instances persist until
dispose()is called. After dispose, the sameidcreates a fresh instance. - When
setup({ expose: true })is called,window.nmMPlayeris set to the factory for console access.
const player = nmMPlayer('main'); // creates or retrieves 'main'
const same = nmMPlayer('main'); // same instance
player === same; // true
Setup
setup(opts)
setup(opts: MusicPlayerConfig<T>): NMMusicPlayer<T>
Initialize the player with config. Returns the player for chaining. See Configuration for all options.
ready()
ready(): Promise<void>
Resolves when setup is complete and all plugins’ use() promises have resolved.
Safe to await before calling transport methods.
dispose()
dispose(): void
Tears down the player: stops playback, disposes all plugins, removes event listeners, frees the audio backend. The instance is removed from the internal registry.
Transport
play(opts?)
play(opts?: ActionOptions): Promise<void>
Start or resume playback.
pause(opts?)
pause(opts?: ActionOptions): Promise<void>
Pause playback.
stop(opts?)
stop(opts?: ActionOptions): Promise<void>
Stop playback and reset position to 0.
togglePlayback(opts?)
togglePlayback(opts?: ActionOptions): Promise<void>
Toggle between play and pause.
restart(opts?)
restart(opts?: ActionOptions): Promise<void>
Seek to 0 and play.
Queue navigation
next(opts?)
next(opts?: ActionOptions): Promise<void>
Advance to the next track.
previous(opts?)
previous(opts?: ActionOptions): Promise<void>
Return to the previous track.
seekToIndex(position, opts?)
seekToIndex(position: number, opts?: ActionOptions): void
Navigate to a playlist item by 1-based ordinal position: seekToIndex(1) loads the first item, seekToIndex(queueLength()) the last. Throws RangeError for non-positive-integer values; out-of-range positions are ignored.
peekNext()
peekNext(): T | undefined
Return the next track without changing the current track.
peekPrevious()
peekPrevious(): T | undefined
Return the previous track without changing the current track.
Current track
item()
item(): T | undefined
Return the currently loaded track. (current is the event name; the method is item().)
item(target, opts?)
item(target: T | string | number, opts?: ActionOptions): void
Set the current track by item, id, or index. The target must be in the queue.
index()
index(): number
Index of the current track in the queue. Returns -1 if no track is loaded.
load(item, opts?)
load(item: T, opts?: LoadOptions): Promise<void>
Load a single track into the player without requiring it to be in the queue first. Does not start playback.
Time
time()
time(): number
Return the current playback position in seconds.
time(seconds, opts?)
time(seconds: number, opts?: ActionOptions): Promise<void>
Seek to a position in seconds.
duration()
duration(): number
Total duration of the current track in seconds.
buffered()
buffered(): number
Seconds of audio buffered ahead of the current position.
bufferedRanges()
bufferedRanges(): TimeRanges
All buffered time ranges.
seekable()
seekable(): TimeRanges
Seekable time ranges.
forward(seconds?, opts?)
forward(seconds?: number, opts?: ActionOptions): Promise<void>
Skip forward by seconds seconds (default: 5).
rewind(seconds?, opts?)
rewind(seconds?: number, opts?: ActionOptions): Promise<void>
Skip backward by seconds seconds (default: 5).
seekByPercentage(pct, opts?)
seekByPercentage(pct: number, opts?: ActionOptions): void
Seek to a percentage of the total duration (0–100).
timeData()
timeData(): TimeState
Full time snapshot: { position, duration, buffered, remaining, percentage }. All values in seconds except percentage (0–100).
Volume
Volume scale: 0–100.
volume()
volume(): number
Return the current volume (0–100). Returns 0 when muted regardless of the stored pre-mute level.
volume(level)
volume(level: number): void
Set the volume. Clamped to [0, 100]. Emits volume. No-op if cancelled by beforeMutation.
player.volume(80); // 80%
const level = player.volume(); // 80
mute()
mute(): void
Silence output.
Persists the current level so unmute() can restore it.
Emits mute with { muted: true }.
No-op when already muted.
unmute()
unmute(): void
Restore the pre-mute volume.
Emits mute with { muted: false }.
No-op when already unmuted.
toggleMute()
toggleMute(): void
Toggle between muted and unmuted.
volumeUp(step?)
volumeUp(step?: number): void
Increase volume by step percentage points. Default: 5.
volumeDown(step?)
volumeDown(step?: number): void
Decrease volume by step percentage points. Default: 5.
volumeState()
volumeState(): VolumeState
Return VolumeState enum (VolumeState.UNMUTED or VolumeState.MUTED).
Playback rate
playbackRate()
playbackRate(): number
Current playback rate (default: 1.0).
playbackRate(rate)
playbackRate(rate: number): void
Set playback rate.
playbackRates()
playbackRates(): number[]
Available playback rate options.
Shuffle and repeat
shuffleState()
shuffleState(): ShuffleState
Current shuffle state (ShuffleState.OFF | ShuffleState.ON).
shuffleState(state)
shuffleState(state: ShuffleState | boolean): void
Set shuffle state. Accepts a ShuffleState enum value or a convenience boolean (true = ShuffleState.ON, false = ShuffleState.OFF).
repeatState()
repeatState(): RepeatState
Current repeat state (RepeatState.OFF | RepeatState.ONE | RepeatState.ALL).
repeatState(state)
repeatState(state: RepeatState): void
Set repeat state.
Queue management
queue()
queue(): ReadonlyArray<T>
Return the current queue.
queue(items, opts?)
queue(items: T[], opts?: ActionOptions): void
Replace the queue.
queueAppend(items, opts?)
queueAppend(items: T | T[], opts?: ActionOptions): void
Append one or more tracks to the end of the queue.
queuePrepend(items, opts?)
queuePrepend(items: T | T[], opts?: ActionOptions): void
Insert one or more tracks at the start of the queue.
queueRemove(id, opts?)
queueRemove(id: string | number, opts?: ActionOptions): void
Remove a track from the queue by id.
queueRemoveAt(index, opts?)
queueRemoveAt(index: number, opts?: ActionOptions): void
Remove the track at a specific index.
queueInsert(item, index, opts?)
queueInsert(item: T | T[], index: number, opts?: ActionOptions): void
Insert a track at a specific index.
queueMove(from, to, opts?)
queueMove(from: number, to: number, opts?: ActionOptions): void
Move a track from one index to another.
queueClear(opts?)
queueClear(opts?: ActionOptions): void
Remove all tracks from the queue.
queueShuffle(opts?)
queueShuffle(opts?: ActionOptions): void
Shuffle the current queue in place.
queueSort(fn, opts?)
queueSort(fn: (a: T, b: T) => number, opts?: ActionOptions): void
Sort the queue by a comparator function.
queueIndexOf(id)
queueIndexOf(id: string | number): number
Return the index of a track by id, or -1 if not found.
queueLength()
queueLength(): number
Number of tracks in the queue.
Backlog
The backlog is a secondary list for tracks that have been played.
Used as a history buffer for previous().
backlog()
backlog(): ReadonlyArray<T>
backlog(items)
backlog(items: T[]): void
backlogAppend(items)
backlogAppend(items: T | T[]): void
backlogRemove(id)
backlogRemove(id: string | number): void
backlogClear()
backlogClear(): void
Crossfade
crossfadeTo(track, opts?)
crossfadeTo(track: T, opts?: CrossfadeOptions & ActionOptions): Promise<void>
Start a crossfade to the given track immediately.
Uses crossfadeDefaults from setup if no opts are provided.
isTransitioning()
isTransitioning(): boolean
Returns true if a crossfade is in progress.
Audio output
audioOutputs()
audioOutputs(): Promise<MediaDeviceInfo[]>
Enumerate available audio output devices.
selectAudioOutput()
selectAudioOutput(): Promise<MediaDeviceInfo | null>
Opens the browser’s audio output device picker.
Returns the selected MediaDeviceInfo, or null when the user cancels or the API is unavailable.
audioOutput()
audioOutput(): Promise<string | null>
audioOutput(deviceId: string): Promise<void>
Get the current audio output device id (returns null when no device is selected), or route audio to a specific device by id.
Audio tracks
audioTracks()
audioTracks(): AudioTrack[]
Available audio tracks exposed by the current backend.
Most local files surface a single track; multi-track sources (HLS audio renditions, container with multiple <audio> streams, etc.) surface one entry per language/variant.
audioTrack()
audioTrack(): CurrentAudioTrackSelection | null
The current audio track selection, or null when no explicit selection has been made.
The returned object has index: number (position in the audioTracks() list) and track: AudioTrack (full metadata).
audioTrack(index)
audioTrack(index: number): void
Switch to an audio track by index.
Subtitles and chapters
subtitles()
subtitles(): never // throws NotImplementedError
Audio backends do not expose subtitle tracks.
Calling subtitles() on the music player always throws NotImplementedError (code: core:not-implemented/subtitles).
Catch by type if you share code between video and music players:
try {
const tracks = player.subtitles();
} catch (error) {
if (error instanceof NotImplementedError) {
// expected on music player; audio backends don't have subtitle tracks
}
}
subtitle()
subtitle(): CurrentSubtitleSelection | null
The current subtitle selection, or null when subtitles are off.
The returned object has index: number (position in the subtitles() list) and track: SubtitleTrack (full metadata).
Note: the music player’s subtitles() always throws NotImplementedError; this method is present for interface compatibility only.
subtitle(index)
subtitle(index: number | null): void
chapters()
chapters(): Chapter[]
Backend
backend()
backend(): IAudioBackend
Return the active audio backend instance.
Instantiates WebAudioBackend or AudioElementBackend on first call (based on setup({ backend }) option).
backend(kind)
backend(kind: 'webaudio' | 'audio-element'): Promise<void>
Switch backends at runtime. Disposes the current backend, creates the new one, and re-wires events. The player remains in its current playback state (paused).
audioContext()
audioContext(): AudioContext | undefined
The underlying AudioContext. Only available when using WebAudioBackend.
Auth
auth() / auth(config)
auth(): Readonly<AuthConfig> | undefined
auth(config: AuthConfig): void
auth(partial: Partial<AuthConfig>): void
Read or merge auth config at runtime.
Pass a full AuthConfig to replace, or a Partial<AuthConfig> to update only specified fields.
refreshAuth()
refreshAuth(): Promise<void>
Trigger a manual auth refresh via auth.refreshOnUnauthenticated().
URL
baseUrl() / baseUrl(url)
baseUrl(): string | undefined
baseUrl(url: string): void
Get or set the base URL prepended to relative audio source URLs.
resolveUrl(url, category?)
resolveUrl(url: string, category?: UrlCategory): Promise<ResolvedUrl>
Resolve a URL through the configured urlResolver.
Use for URLs that cannot carry Authorization headers.
UrlCategory values: 'media' | 'subtitle' | 'poster' | 'thumbnail' | 'chapter' | 'license' | 'cast'.
urlResolver() / urlResolver(fn)
urlResolver(): IUrlResolver | undefined
urlResolver(resolver: IUrlResolver | undefined): void
Plugins
addPlugin(PluginClass, opts?)
addPlugin<P extends Plugin>(Cls: PluginCtorWithId & (new () => P), opts?: P['opts']): NMMusicPlayer<T>
Register and activate a plugin. Returns the player for chaining.
getPlugin(PluginClass)
getPlugin<P extends object>(Cls: PluginCtorWithId & (new () => P)): P | undefined
Retrieve a registered plugin instance, typed.
getPluginById(id)
getPluginById(id: string): Plugin | undefined
Retrieve a plugin by its string id.
removePlugin(PluginClass, opts?)
removePlugin<P extends Plugin>(Cls: PluginCtorWithId & (new () => P)): void
Dispose and remove a plugin, plus any plugins that depend on it (cascade is the default).
Pass { cascade: false } to instead throw core:plugin/has-dependents when other plugins depend on it.
plugins()
plugins(): Plugin[]
All currently registered plugins.
Phase and diagnostics
phase()
phase(): PlayerPhase
Current player phase: 'idle' | 'setup' | 'ready' | 'loading' | 'starting' | 'playing' | 'paused' | 'buffering' | 'seeking' | 'ended' | 'stopped' | 'disposing' | 'disposed'.
playState()
playState(): PlayState
Current play state enum: PlayState.IDLE | PlayState.LOADING | PlayState.PLAYING | PlayState.PAUSED | PlayState.STOPPED | PlayState.ERROR.
metrics()
metrics(): PlaybackMetrics
Playback metrics snapshot.
Always returns a PlaybackMetrics object.
Individual counters unavailable from the audio backend (ttfb, avgBitrate, droppedFrames, decoderStalls) are null.
Guard before use: if (metrics.droppedFrames !== null) { ... }.
See Core Metrics for the full counter matrix.
recordMetric(name, value)
recordMetric(name: string, value: number): void
Record a custom metric.
bandwidth()
bandwidth(): number
Current estimated bandwidth in bits/sec.
now()
now(): number
Monotonic clock value from the configured IClock.
Use for distributed time sync in group-listening scenarios.
i18n
t(key, vars?)
t(key: string, vars?: Record<string, string>): string
Translate a key using the configured translator. Missing keys fall back to the key itself.
language() / language(lang)
language(): string
language(lang: string): Promise<void>
Get or set the active language (BCP-47).
addTranslations(bundle)
addTranslations(bundle: Translations): void
removeTranslations(prefix, lang?)
removeTranslations(prefix: string, lang?: string): void
Device capabilities
isTv(), isMobile(), isDesktop()
isTv(): boolean
isMobile(): boolean
isDesktop(): boolean
device()
device(): DeviceCapabilities
Full device capability snapshot.
canPlay(profile)
canPlay(profile: {
contentType: string;
width?: number;
height?: number;
bitrate?: number;
framerate?: number;
}): Promise<CanPlayResult>
Query MediaCapabilities.decodingInfo().
Used internally to probe format support before loading.
Bandwidth estimation
bandwidth()
bandwidth(): number
Estimated bandwidth in bits/sec.
bandwidthEstimator() / bandwidthEstimator(fn)
bandwidthEstimator(): (() => number) | undefined
bandwidthEstimator(fn: () => number): void
Stream registration
registerStream(factory, prepend?)
registerStream(factory: IStreamFactory, prepend?: boolean): this
unregisterStream(id)
unregisterStream(id: string): this
streams()
streams(): ReadonlyArray<string>
getStreamFactory(id)
getStreamFactory(id: string): IStreamFactory | undefined
Cue parsers
registerCueParser(parser, prepend?)
registerCueParser(parser: ICueParser, prepend?: boolean): void
Register a custom cue parser (LRC, VTT, or custom subtitle format).
unregisterCueParser(id)
unregisterCueParser(id: string): void
resolveCueParser(url)
resolveCueParser(url: string): ICueParser | undefined
Preload and transition strategies
setPreloadStrategy(strategy)
setPreloadStrategy(strategy: IPreloadStrategy): void
Default: MusicPreloadStrategy (preloads 10 s before end).
preloadStrategy()
preloadStrategy(): IPreloadStrategy
setTransitionStrategy(strategy)
setTransitionStrategy(strategy: ITransitionStrategy): void
Default: CrossfadeTransitionStrategy (3 s crossfade, equal-power curve).
transitionStrategy()
transitionStrategy(): ITransitionStrategy
Setup state and diagnostics
setupState()
setupState(): SetupState
dispatching()
dispatching(): ReadonlyArray<string>
Names of all active before* events in flight.
bufferState()
bufferState(): BufferState
networkState()
networkState(): NetworkState
visibilityState()
visibilityState(): VisibilityState // 'visible' | 'hidden'
streamState()
streamState(): string
qualityMode() / qualityMode(target)
qualityMode(): QualityState
qualityMode(target: number | 'auto'): void
audioTrackMode() / audioTrackMode(idx)
audioTrackMode(): AudioTrackState
audioTrackMode(idx: number): void
Cast
castState()
castState(): CastState
transferTo(target)
transferTo(target: CastTarget): Promise<void>
// type CastTarget = 'cast' | 'airplay' | 'remote-playback' | 'local'
Hand off playback to a Chromecast or AirPlay device, or pass 'local' to pull playback back.
CastTarget is exported from @nomercy-entertainment/nomercy-player-core. See Cast and Remote Playback.
Announce (accessibility)
announce(text, level?)
announce(text: string, level?: 'polite' | 'assertive'): void
ARIA live-region announcement for screen readers.
Event API
on(event, handler)
on<K extends keyof MusicEventMap>(event: K, handler: (payload: MusicEventMap[K]) => void): void
off(event, handler)
off<K extends keyof MusicEventMap>(event: K, handler: (payload: MusicEventMap[K]) => void): void
once(event, handler)
once<K extends keyof MusicEventMap>(event: K, handler: (payload: MusicEventMap[K]) => void): void
To subscribe to another plugin’s events from outside a plugin, use the namespaced string form:
player.on('plugin:<id>:<event>', handler);
// Example:
player.on('plugin:lyrics:lineEnter', ({ text }) => { /* ... */ });
The on(PluginClass, event, handler) class form is protected — it is available inside plugin class bodies only, not from consumer code.