Skip to content

AudioPlayer

Manages audio playback using the Web Audio API with support for both complete and streaming playback modes.

Defined in: src/core/audio/AudioPlayer.ts:124

Manages audio playback using the Web Audio API with support for both complete and streaming playback modes.

Remarks

AudioPlayer creates and manages an AudioContext and plays audio through AudioBufferSourceNode instances. It maintains an internal queue for streaming playback and implements minimum-buffer-duration gating to prevent choppy output.

The class tracks its state via AudioPlaybackState values: 'idle', 'buffering', 'playing', 'paused', and 'stopped'.

Lifecycle callbacks can be registered via setCallbacks() to respond to playback start, end, and error events.

Example

import { AudioPlayer } from './AudioPlayer';

const player = new AudioPlayer({ minBufferDuration: 200 }, logger);

// Set up lifecycle callbacks
player.setCallbacks({
  onStart: () => console.log('Started speaking'),
  onEnd: () => console.log('Finished speaking'),
  onError: (err) => console.error('Playback error:', err),
});

// Streaming playback: set metadata, then add chunks as they arrive
player.setMetadata({ sampleRate: 24000, encoding: 'linear16', channels: 1 });
for await (const chunk of ttsStream) {
  await player.addChunk(chunk);
}

// Wait for all audio to finish playing
await player.waitForCompletion();

// Complete playback: play a full audio blob
await player.play(audioBlob);

// Clean up
await player.dispose();

See

Constructors

Constructor

new AudioPlayer(config?, logger?): AudioPlayer;

Defined in: src/core/audio/AudioPlayer.ts:149

Creates a new AudioPlayer instance.

Parameters

ParameterTypeDescription
configPartial<AudioOutputConfig>Partial audio output configuration. Missing fields are filled from DEFAULT_AUDIO_OUTPUT_CONFIG.
logger?LoggerOptional Logger instance. A child logger named 'AudioPlayer' is created if provided.

Returns

AudioPlayer

Remarks

The instance starts in the 'idle' state with an empty audio queue. The AudioContext is created lazily on the first playback request.

Methods

addChunk()

addChunk(chunk): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:320

Adds an audio chunk to the streaming playback queue.

Parameters

ParameterTypeDescription
chunkAudioChunkThe AudioChunk to add to the playback queue.

Returns

Promise<void>

Remarks

Chunks are queued internally and processed in order. If the queue processor is not already running, it is started automatically. The processor waits for a minimum buffer duration (see AudioOutputConfig.minBufferDuration) before beginning playback to prevent choppy output.

Call setMetadata() before adding chunks to ensure correct decoding and buffer duration estimation.

Example

// Add chunks as they arrive from TTS provider
ttsProvider.on('audio', async (chunk) => {
  await player.addChunk(chunk);
});

dispose()

dispose(): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:722

Disposes of the player by stopping playback and closing the AudioContext.

Returns

Promise<void>

Remarks

This method stops any active playback, clears the queue, closes the AudioContext, and nullifies all callback references. After disposal, the instance should not be reused.


getAudioContext()

getAudioContext(): AudioContext | null;

Defined in: src/core/audio/AudioPlayer.ts:745

Returns the underlying AudioContext, if one has been created.

Returns

AudioContext | null

The active AudioContext, or null if none exists.

Remarks

This is intended for advanced use cases where direct access to the audio context is needed. Returns null if no playback has been initiated or if the player has been disposed.


getConfig()

getConfig(): AudioOutputConfig;

Defined in: src/core/audio/AudioPlayer.ts:759

Returns a copy of the current audio output configuration.

Returns

AudioOutputConfig

A copy of the current AudioOutputConfig.

Remarks

The returned object is a shallow copy; modifying it does not affect the internal configuration. Use updateConfig() to change settings.


getState()

getState(): AudioPlaybackState;

Defined in: src/core/audio/AudioPlayer.ts:160

Returns the current playback state.

Returns

AudioPlaybackState

The current AudioPlaybackState ('idle', 'buffering', 'playing', 'paused', or 'stopped').


isPlaying()

isPlaying(): boolean;

Defined in: src/core/audio/AudioPlayer.ts:174

Checks whether the player is currently playing audio.

Returns

boolean

true if the state is 'playing', false otherwise.

Remarks

Returns true only when in the 'playing' state. Unlike SimpleAudioPlaybackStateMachine.isPlaying, this does not include the 'buffering' state.


pause()

pause(): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:603

Pauses audio playback by suspending the AudioContext.

Returns

Promise<void>

Remarks

If the player is not in the 'playing' state, this method logs a warning and returns without error.


play()

play(audioBlob): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:279

Plays a complete audio blob.

Parameters

ParameterTypeDescription
audioBlobBlobThe audio data as a Blob (e.g. WAV, MP3, OGG).

Returns

Promise<void>

Remarks

The blob is decoded via AudioContext.decodeAudioData and played through an AudioBufferSourceNode. This method is intended for one-shot playback of a complete audio file, not for streaming.

Throws

AudioPlaybackError if decoding or playback fails.

Example

const response = await fetch('/audio/greeting.wav');
const blob = await response.blob();
await player.play(blob);

resume()

resume(): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:623

Resumes audio playback from a paused state.

Returns

Promise<void>

Remarks

If the player is not in the 'paused' state, this method logs a warning and returns without error.


setCallbacks()

setCallbacks(callbacks): void;

Defined in: src/core/audio/AudioPlayer.ts:224

Registers lifecycle callbacks for playback events.

Parameters

ParameterTypeDescription
callbacks{ onEnd?: PlaybackEndCallback; onError?: PlaybackErrorCallback; onStart?: PlaybackStartCallback; }An object with optional onStart, onEnd, and onError callback properties.
callbacks.onEnd?PlaybackEndCallback-
callbacks.onError?PlaybackErrorCallback-
callbacks.onStart?PlaybackStartCallback-

Returns

void

Remarks

Pass undefined or omit a callback to leave it unset. Previously registered callbacks are replaced. Pass null explicitly is not needed; omitted callbacks default to null internally.

Example

player.setCallbacks({
  onStart: () => ui.showSpeaking(),
  onEnd: () => ui.hideSpeaking(),
  onError: (err) => ui.showError(err.message),
});

setMetadata()

setMetadata(metadata): void;

Defined in: src/core/audio/AudioPlayer.ts:255

Sets audio metadata for streaming playback.

Parameters

ParameterTypeDescription
metadataAudioMetadataThe AudioMetadata describing the audio format (sample rate, encoding, channels, etc.).

Returns

void

Remarks

Metadata is used to calculate buffer durations and to decode raw PCM chunks when standard decodeAudioData fails. This should be called before adding streaming chunks via addChunk().

Example

player.setMetadata({
  sampleRate: 24000,
  encoding: 'linear16',
  channels: 1,
  bitDepth: 16,
});

stop()

stop(): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:650

Stops playback immediately and clears the audio queue.

Returns

Promise<void>

Remarks

This method:

  1. Stops the current AudioBufferSourceNode (ignoring errors if already stopped).
  2. Clears the chunk queue.
  3. Resets the queue-processing flag.
  4. Sets the state to 'stopped' and clears metadata.
  5. Invokes the onPlaybackEnd callback.

After stopping, new chunks can be queued via addChunk() to start a new playback session.


updateConfig()

updateConfig(config): void;

Defined in: src/core/audio/AudioPlayer.ts:773

Updates the audio output configuration.

Parameters

ParameterTypeDescription
configPartial<AudioOutputConfig>Partial configuration to merge with the current settings.

Returns

void

Remarks

Configuration changes may affect subsequent playback behavior (e.g. buffer duration thresholds). Some settings (like sampleRate) only take effect when a new AudioContext is created.


waitForCompletion()

waitForCompletion(timeoutMs?): Promise<void>;

Defined in: src/core/audio/AudioPlayer.ts:691

Waits for all queued audio to finish playing.

Parameters

ParameterTypeDefault valueDescription
timeoutMsnumber30000Maximum wait time in milliseconds.

Returns

Promise<void>

Remarks

Polls every 50ms until the queue is empty, the queue processor has finished, and the state returns to 'idle'. If the timeout is exceeded, a warning is logged and the method returns (audio may still be playing).

Default Value

30000

Example

// Add all chunks, then wait for playback to complete
for (const chunk of chunks) {
  await player.addChunk(chunk);
}
await player.waitForCompletion(10000); // wait up to 10 seconds

© 2026 CompositeVoice. All rights reserved.

Font size
Contrast
Motion
Transparency