Skip to content

API Methods Reference

All public methods on NMMusicPlayer<T>. Methods follow the overloaded getter/setter pattern: method() reads, method(value) writes.

Factory

nmMPlayer(id?)

TypeScript
nmMPlayer(id?: string | number): NMMusicPlayer<MusicPlaylistItem>
nmMPlayer<T extends MusicPlaylistItem>(id?: string | number): NMMusicPlayer<T>

Creates or retrieves a named player instance.

  • id is optional. When omitted, the core generates a unique id.
  • Two calls with the same id return 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 same id creates a fresh instance.
  • When setup({ expose: true }) is called, window.nmMPlayer is set to the factory for console access.
TypeScript
const player = nmMPlayer('main'); // creates or retrieves 'main'
const same = nmMPlayer('main'); // same instance
player === same; // true

Setup

setup(opts)

TypeScript
setup(opts: MusicPlayerConfig<T>): NMMusicPlayer<T>

Initialize the player with config. Returns the player for chaining. See Configuration for all options.

ready()

TypeScript
ready(): Promise<void>

Resolves when setup is complete and all plugins’ use() promises have resolved. Safe to await before calling transport methods.

dispose()

TypeScript
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?)

TypeScript
play(opts?: ActionOptions): Promise<void>

Start or resume playback.

pause(opts?)

TypeScript
pause(opts?: ActionOptions): Promise<void>

Pause playback.

stop(opts?)

TypeScript
stop(opts?: ActionOptions): Promise<void>

Stop playback and reset position to 0.

togglePlayback(opts?)

TypeScript
togglePlayback(opts?: ActionOptions): Promise<void>

Toggle between play and pause.

restart(opts?)

TypeScript
restart(opts?: ActionOptions): Promise<void>

Seek to 0 and play.

Queue navigation

next(opts?)

TypeScript
next(opts?: ActionOptions): Promise<void>

Advance to the next track.

previous(opts?)

TypeScript
previous(opts?: ActionOptions): Promise<void>

Return to the previous track.

seekToIndex(position, opts?)

TypeScript
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()

TypeScript
peekNext(): T | undefined

Return the next track without changing the current track.

peekPrevious()

TypeScript
peekPrevious(): T | undefined

Return the previous track without changing the current track.

Current track

item()

TypeScript
item(): T | undefined

Return the currently loaded track. (current is the event name; the method is item().)

item(target, opts?)

TypeScript
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()

TypeScript
index(): number

Index of the current track in the queue. Returns -1 if no track is loaded.

load(item, opts?)

TypeScript
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()

TypeScript
time(): number

Return the current playback position in seconds.

time(seconds, opts?)

TypeScript
time(seconds: number, opts?: ActionOptions): Promise<void>

Seek to a position in seconds.

duration()

TypeScript
duration(): number

Total duration of the current track in seconds.

buffered()

TypeScript
buffered(): number

Seconds of audio buffered ahead of the current position.

bufferedRanges()

TypeScript
bufferedRanges(): TimeRanges

All buffered time ranges.

seekable()

TypeScript
seekable(): TimeRanges

Seekable time ranges.

forward(seconds?, opts?)

TypeScript
forward(seconds?: number, opts?: ActionOptions): Promise<void>

Skip forward by seconds seconds (default: 5).

rewind(seconds?, opts?)

TypeScript
rewind(seconds?: number, opts?: ActionOptions): Promise<void>

Skip backward by seconds seconds (default: 5).

seekByPercentage(pct, opts?)

TypeScript
seekByPercentage(pct: number, opts?: ActionOptions): void

Seek to a percentage of the total duration (0–100).

timeData()

TypeScript
timeData(): TimeState

Full time snapshot: { position, duration, buffered, remaining, percentage }. All values in seconds except percentage (0–100).

Volume

Volume scale: 0–100.

volume()

TypeScript
volume(): number

Return the current volume (0–100). Returns 0 when muted regardless of the stored pre-mute level.

volume(level)

TypeScript
volume(level: number): void

Set the volume. Clamped to [0, 100]. Emits volume. No-op if cancelled by beforeMutation.

TypeScript
player.volume(80); // 80%
const level = player.volume(); // 80

mute()

TypeScript
mute(): void

Silence output. Persists the current level so unmute() can restore it. Emits mute with { muted: true }. No-op when already muted.

unmute()

TypeScript
unmute(): void

Restore the pre-mute volume. Emits mute with { muted: false }. No-op when already unmuted.

toggleMute()

TypeScript
toggleMute(): void

Toggle between muted and unmuted.

volumeUp(step?)

TypeScript
volumeUp(step?: number): void

Increase volume by step percentage points. Default: 5.

volumeDown(step?)

TypeScript
volumeDown(step?: number): void

Decrease volume by step percentage points. Default: 5.

volumeState()

TypeScript
volumeState(): VolumeState

Return VolumeState enum (VolumeState.UNMUTED or VolumeState.MUTED).

Playback rate

playbackRate()

TypeScript
playbackRate(): number

Current playback rate (default: 1.0).

playbackRate(rate)

TypeScript
playbackRate(rate: number): void

Set playback rate.

playbackRates()

TypeScript
playbackRates(): number[]

Available playback rate options.

Shuffle and repeat

shuffleState()

TypeScript
shuffleState(): ShuffleState

Current shuffle state (ShuffleState.OFF | ShuffleState.ON).

shuffleState(state)

TypeScript
shuffleState(state: ShuffleState | boolean): void

Set shuffle state. Accepts a ShuffleState enum value or a convenience boolean (true = ShuffleState.ON, false = ShuffleState.OFF).

repeatState()

TypeScript
repeatState(): RepeatState

Current repeat state (RepeatState.OFF | RepeatState.ONE | RepeatState.ALL).

repeatState(state)

TypeScript
repeatState(state: RepeatState): void

Set repeat state.

Queue management

queue()

TypeScript
queue(): ReadonlyArray<T>

Return the current queue.

queue(items, opts?)

TypeScript
queue(items: T[], opts?: ActionOptions): void

Replace the queue.

queueAppend(items, opts?)

TypeScript
queueAppend(items: T | T[], opts?: ActionOptions): void

Append one or more tracks to the end of the queue.

queuePrepend(items, opts?)

TypeScript
queuePrepend(items: T | T[], opts?: ActionOptions): void

Insert one or more tracks at the start of the queue.

queueRemove(id, opts?)

TypeScript
queueRemove(id: string | number, opts?: ActionOptions): void

Remove a track from the queue by id.

queueRemoveAt(index, opts?)

TypeScript
queueRemoveAt(index: number, opts?: ActionOptions): void

Remove the track at a specific index.

queueInsert(item, index, opts?)

TypeScript
queueInsert(item: T | T[], index: number, opts?: ActionOptions): void

Insert a track at a specific index.

queueMove(from, to, opts?)

TypeScript
queueMove(from: number, to: number, opts?: ActionOptions): void

Move a track from one index to another.

queueClear(opts?)

TypeScript
queueClear(opts?: ActionOptions): void

Remove all tracks from the queue.

queueShuffle(opts?)

TypeScript
queueShuffle(opts?: ActionOptions): void

Shuffle the current queue in place.

queueSort(fn, opts?)

TypeScript
queueSort(fn: (a: T, b: T) => number, opts?: ActionOptions): void

Sort the queue by a comparator function.

queueIndexOf(id)

TypeScript
queueIndexOf(id: string | number): number

Return the index of a track by id, or -1 if not found.

queueLength()

TypeScript
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()

TypeScript
backlog(): ReadonlyArray<T>

backlog(items)

TypeScript
backlog(items: T[]): void

backlogAppend(items)

TypeScript
backlogAppend(items: T | T[]): void

backlogRemove(id)

TypeScript
backlogRemove(id: string | number): void

backlogClear()

TypeScript
backlogClear(): void

Crossfade

crossfadeTo(track, opts?)

TypeScript
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()

TypeScript
isTransitioning(): boolean

Returns true if a crossfade is in progress.

Audio output

audioOutputs()

TypeScript
audioOutputs(): Promise<MediaDeviceInfo[]>

Enumerate available audio output devices.

selectAudioOutput()

TypeScript
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()

TypeScript
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()

TypeScript
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()

TypeScript
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)

TypeScript
audioTrack(index: number): void

Switch to an audio track by index.

Subtitles and chapters

subtitles()

TypeScript
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:

TypeScript
try {
const tracks = player.subtitles();
} catch (error) {
if (error instanceof NotImplementedError) {
// expected on music player; audio backends don't have subtitle tracks
}
}

subtitle()

TypeScript
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)

TypeScript
subtitle(index: number | null): void

chapters()

TypeScript
chapters(): Chapter[]

Backend

backend()

TypeScript
backend(): IAudioBackend

Return the active audio backend instance. Instantiates WebAudioBackend or AudioElementBackend on first call (based on setup({ backend }) option).

backend(kind)

TypeScript
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()

TypeScript
audioContext(): AudioContext | undefined

The underlying AudioContext. Only available when using WebAudioBackend.

Auth

auth() / auth(config)

TypeScript
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()

TypeScript
refreshAuth(): Promise<void>

Trigger a manual auth refresh via auth.refreshOnUnauthenticated().

URL

baseUrl() / baseUrl(url)

TypeScript
baseUrl(): string | undefined
baseUrl(url: string): void

Get or set the base URL prepended to relative audio source URLs.

resolveUrl(url, category?)

TypeScript
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)

TypeScript
urlResolver(): IUrlResolver | undefined
urlResolver(resolver: IUrlResolver | undefined): void

Plugins

addPlugin(PluginClass, opts?)

TypeScript
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)

TypeScript
getPlugin<P extends object>(Cls: PluginCtorWithId & (new () => P)): P | undefined

Retrieve a registered plugin instance, typed.

getPluginById(id)

TypeScript
getPluginById(id: string): Plugin | undefined

Retrieve a plugin by its string id.

removePlugin(PluginClass, opts?)

TypeScript
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()

TypeScript
plugins(): Plugin[]

All currently registered plugins.

Phase and diagnostics

phase()

TypeScript
phase(): PlayerPhase

Current player phase: 'idle' | 'setup' | 'ready' | 'loading' | 'starting' | 'playing' | 'paused' | 'buffering' | 'seeking' | 'ended' | 'stopped' | 'disposing' | 'disposed'.

playState()

TypeScript
playState(): PlayState

Current play state enum: PlayState.IDLE | PlayState.LOADING | PlayState.PLAYING | PlayState.PAUSED | PlayState.STOPPED | PlayState.ERROR.

metrics()

TypeScript
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)

TypeScript
recordMetric(name: string, value: number): void

Record a custom metric.

bandwidth()

TypeScript
bandwidth(): number

Current estimated bandwidth in bits/sec.

now()

TypeScript
now(): number

Monotonic clock value from the configured IClock. Use for distributed time sync in group-listening scenarios.

i18n

t(key, vars?)

TypeScript
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)

TypeScript
language(): string
language(lang: string): Promise<void>

Get or set the active language (BCP-47).

addTranslations(bundle)

TypeScript
addTranslations(bundle: Translations): void

removeTranslations(prefix, lang?)

TypeScript
removeTranslations(prefix: string, lang?: string): void

Device capabilities

isTv(), isMobile(), isDesktop()

TypeScript
isTv(): boolean
isMobile(): boolean
isDesktop(): boolean

device()

TypeScript
device(): DeviceCapabilities

Full device capability snapshot.

canPlay(profile)

TypeScript
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()

TypeScript
bandwidth(): number

Estimated bandwidth in bits/sec.

bandwidthEstimator() / bandwidthEstimator(fn)

TypeScript
bandwidthEstimator(): (() => number) | undefined
bandwidthEstimator(fn: () => number): void

Stream registration

registerStream(factory, prepend?)

TypeScript
registerStream(factory: IStreamFactory, prepend?: boolean): this

unregisterStream(id)

TypeScript
unregisterStream(id: string): this

streams()

TypeScript
streams(): ReadonlyArray<string>

getStreamFactory(id)

TypeScript
getStreamFactory(id: string): IStreamFactory | undefined

Cue parsers

registerCueParser(parser, prepend?)

TypeScript
registerCueParser(parser: ICueParser, prepend?: boolean): void

Register a custom cue parser (LRC, VTT, or custom subtitle format).

unregisterCueParser(id)

TypeScript
unregisterCueParser(id: string): void

resolveCueParser(url)

TypeScript
resolveCueParser(url: string): ICueParser | undefined

Preload and transition strategies

setPreloadStrategy(strategy)

TypeScript
setPreloadStrategy(strategy: IPreloadStrategy): void

Default: MusicPreloadStrategy (preloads 10 s before end).

preloadStrategy()

TypeScript
preloadStrategy(): IPreloadStrategy

setTransitionStrategy(strategy)

TypeScript
setTransitionStrategy(strategy: ITransitionStrategy): void

Default: CrossfadeTransitionStrategy (3 s crossfade, equal-power curve).

transitionStrategy()

TypeScript
transitionStrategy(): ITransitionStrategy

Setup state and diagnostics

setupState()

TypeScript
setupState(): SetupState

dispatching()

TypeScript
dispatching(): ReadonlyArray<string>

Names of all active before* events in flight.

bufferState()

TypeScript
bufferState(): BufferState

networkState()

TypeScript
networkState(): NetworkState

visibilityState()

TypeScript
visibilityState(): VisibilityState  // 'visible' | 'hidden'

streamState()

TypeScript
streamState(): string

qualityMode() / qualityMode(target)

TypeScript
qualityMode(): QualityState
qualityMode(target: number | 'auto'): void

audioTrackMode() / audioTrackMode(idx)

TypeScript
audioTrackMode(): AudioTrackState
audioTrackMode(idx: number): void

Cast

castState()

TypeScript
castState(): CastState

transferTo(target)

TypeScript
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?)

TypeScript
announce(text: string, level?: 'polite' | 'assertive'): void

ARIA live-region announcement for screen readers.

Event API

on(event, handler)

TypeScript
on<K extends keyof MusicEventMap>(event: K, handler: (payload: MusicEventMap[K]) => void): void

off(event, handler)

TypeScript
off<K extends keyof MusicEventMap>(event: K, handler: (payload: MusicEventMap[K]) => void): void

once(event, handler)

TypeScript
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:

TypeScript
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.