Skip to content

Latest commit

 

History

History
264 lines (200 loc) · 7.33 KB

EncodedAudioChunk.mdx

File metadata and controls

264 lines (200 loc) · 7.33 KB
title EncodedAudioChunk
description Represents a chunk of encoded audio data
icon music

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.

This class follows the [W3C WebCodecs EncodedAudioChunk specification](https://www.w3.org/TR/webcodecs/#encodedaudiochunk-interface).

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)
Configuration object for the encoded chunk. The frame type. For most audio codecs (AAC, MP3, Opus, FLAC), use `'key'` as audio frames are typically independently decodable.
<ParamField body="timestamp" type="number" required>
  Presentation timestamp in **microseconds**. This determines when the audio should be played.
</ParamField>

<ParamField body="duration" type="number">
  Duration of the audio chunk in **microseconds**. Common values:
  - AAC: ~21,333μs (1024 samples at 48kHz)
  - MP3: ~26,122μs (1152 samples at 44.1kHz)
  - Opus: 2,500-60,000μs (configurable)
</ParamField>

<ParamField body="data" type="BufferSource" required>
  The encoded audio data as an `ArrayBuffer` or `TypedArray`.
  The data is copied internally, so you can reuse the source buffer.
</ParamField>
The `type` must be exactly `'key'` or `'delta'`. Any other value will throw a `TypeError`.

Properties

All properties are readonly after construction.

The chunk type. For audio, this is almost always `'key'` since most audio codecs don't use inter-frame prediction. Presentation timestamp in microseconds. Determines when this audio should be played relative to the start of the stream. Duration of this audio chunk in microseconds, or `null` if not specified during construction. 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
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.

```typescript 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);

</Accordion>

---

## Type Definitions

### EncodedAudioChunkType

```typescript
type EncodedAudioChunkType = 'key' | 'delta';
Value Description
'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:

Codec Samples per Frame Duration at 48kHz Duration at 44.1kHz
AAC 1024 ~21,333μs ~23,220μs
MP3 1152 24,000μs ~26,122μs
Opus 120-2880 2,500-60,000μs N/A (always 48kHz)
FLAC Variable Variable Variable
Vorbis Variable Variable Variable

See Also

The video equivalent for encoded video data Encodes AudioData into EncodedAudioChunks Decodes EncodedAudioChunks into AudioData Raw audio sample data