Backend Access
backend()
backend(): IAudioBackend
Return the active audio backend instance.
Instantiates the backend on first call based on the backend option from setup() (default: 'audio-element').
const backend = player.backend();
console.log(backend.kind); // 'audio-element' or 'webaudio'
When backendFactory is configured, the factory is called on the first backend() call to construct the instance.
backend(kind)
backend(kind: AudioBackendKind): Promise<void>
Switch backends at runtime.
Returns a Promise that resolves when the new backend is constructed and wired.
await player.backend('webaudio');
// or:
await player.backend('audio-element');
Switching:
- Disposes the current backend (
dispose()) - Constructs the new backend (via factory if configured, otherwise the built-in default)
- Re-wires all event bridges
- Emits
backend:changedwith{ kind }
The player enters a paused state after the switch. The current position is lost, so start playback explicitly after switching.
AudioBackendKind
type AudioBackendKind = 'audio-element' | 'webaudio';
Discriminating backend type
Do not compare the return value of player.backend() as a string. Use .kind:
// Correct:
if (player.backend().kind === 'webaudio') {
}
// Wrong: backend() returns an IAudioBackend instance, not a string:
if (player.backend() === 'webaudio') {
}
backendFactory
When backendFactory is set in setup(), both the initial backend() call and any backend(kind) swap call invoke the factory instead of constructing a built-in backend:
player.setup({
backendFactory: (kind, config) => {
if (kind === 'webaudio') {
return new MyWebAudioBackend(config);
}
return new MyAudioElementBackend(config);
},
});
The factory receives the resolved kind string and the full MusicPlayerConfig.
Return an object that satisfies IAudioBackend.
'backend:changed' event
The backend:changed event fires after a successful runtime swap.
It is declared in MusicEventMap and is fully typed, no cast required:
player.on('backend:changed', ({ kind }) => {
console.log('Switched to', kind);
});
See also
- Backends overview, for when to pick each backend
- IAudioBackend, the full interface reference
- Configuration, the
backendandbackendFactoryoptions