Skip to main content

EncodedAudioChunk

The EncodedAudioChunk class represents a single chunk of encoded audio data. Unlike video, most audio codecs produce chunks that are all keyframes (independently decodable), though some codecs may use delta encoding.

Quick Example

import { EncodedAudioChunk } from 'node-webcodecs';

// Create from encoded AAC data
const chunk = new EncodedAudioChunk({
  type: 'key',           // Audio chunks are typically all 'key'
  timestamp: 0,          // Presentation time in microseconds
  duration: 21333,       // Duration in microseconds (~21ms for AAC frame)
  data: encodedAACData   // Uint8Array or ArrayBuffer
});

// Access properties
console.log(chunk.type);       // 'key'
console.log(chunk.timestamp);  // 0
console.log(chunk.byteLength); // Size of encoded data

// Copy data to another buffer
const buffer = new Uint8Array(chunk.byteLength);
chunk.copyTo(buffer);

Constructor

Creates a new EncodedAudioChunk from initialization data.
new EncodedAudioChunk(init: EncodedAudioChunkInit)
init
EncodedAudioChunkInit
required
Configuration object for the encoded chunk.
The type must be exactly 'key' or 'delta'. Any other value will throw a TypeError.

Properties

All properties are readonly after construction.
type
'key' | 'delta'
required
The chunk type. For audio, this is almost always 'key' since most audio codecs don’t use inter-frame prediction.
timestamp
number
required
Presentation timestamp in microseconds. Determines when this audio should be played relative to the start of the stream.
duration
number | null
required
Duration of this audio chunk in microseconds, or null if not specified during construction.
byteLength
number
required
Size of the encoded data in bytes. Use this to allocate a buffer for copyTo().

Methods

copyTo()

Copies the encoded audio data to a destination buffer.
chunk.copyTo(destination: BufferSource): void
destination
BufferSource
required
An ArrayBuffer or TypedArray to copy the data into. Must have at least byteLength bytes available.
Throws: TypeError if the destination buffer is smaller than byteLength.
const chunk = new EncodedAudioChunk({
  type: 'key',
  timestamp: 0,
  data: someEncodedData
});

// Allocate buffer with exact size needed
const buffer = new Uint8Array(chunk.byteLength);
chunk.copyTo(buffer);

// Now buffer contains a copy of the encoded data
console.log(`Copied ${buffer.length} bytes of audio`);

Type Definitions

EncodedAudioChunkType

type EncodedAudioChunkType = 'key' | 'delta';
ValueDescription
'key'Keyframe - can be decoded independently (most common for audio)
'delta'Delta frame - requires previous frames (rare for audio)

EncodedAudioChunkInit

interface EncodedAudioChunkInit {
  type: EncodedAudioChunkType;  // Required: 'key' or 'delta'
  timestamp: number;            // Required: microseconds
  duration?: number;            // Optional: microseconds
  data: BufferSource;           // Required: encoded data
}

Usage with AudioEncoder

EncodedAudioChunk objects are typically created by AudioEncoder and passed to your output callback:
import { AudioEncoder, AudioData } from 'node-webcodecs';

const encoder = new AudioEncoder({
  output: (chunk, metadata) => {
    // chunk is an EncodedAudioChunk
    console.log(`Got audio chunk at ${chunk.timestamp}μs`);
    console.log(`Size: ${chunk.byteLength} bytes`);
    console.log(`Duration: ${chunk.duration}μs`);

    // Copy to your own buffer for storage/transmission
    const data = new Uint8Array(chunk.byteLength);
    chunk.copyTo(data);

    // First chunk includes decoder config in metadata
    if (metadata?.decoderConfig) {
      console.log('Decoder config:', metadata.decoderConfig);
    }
  },
  error: (e) => console.error('Encoding error:', e)
});

encoder.configure({
  codec: 'mp4a.40.2',     // AAC-LC
  sampleRate: 48000,
  numberOfChannels: 2,
  bitrate: 128_000
});

Usage with AudioDecoder

Pass EncodedAudioChunk objects to AudioDecoder.decode():
import { AudioDecoder, EncodedAudioChunk } from 'node-webcodecs';

const decoder = new AudioDecoder({
  output: (audioData) => {
    console.log(`Decoded: ${audioData.numberOfFrames} samples`);
    console.log(`Format: ${audioData.format}`);
    audioData.close();  // Don't forget to close!
  },
  error: (e) => console.error('Decoding error:', e)
});

decoder.configure({
  codec: 'mp4a.40.2',
  sampleRate: 48000,
  numberOfChannels: 2
});

// Decode a chunk
const chunk = new EncodedAudioChunk({
  type: 'key',
  timestamp: 0,
  data: aacFrameData
});

decoder.decode(chunk);
await decoder.flush();

Audio Codec Frame Sizes

Different audio codecs produce chunks of different durations:
CodecSamples per FrameDuration at 48kHzDuration at 44.1kHz
AAC1024~21,333μs~23,220μs
MP3115224,000μs~26,122μs
Opus120-28802,500-60,000μsN/A (always 48kHz)
FLACVariableVariableVariable
VorbisVariableVariableVariable

See Also