> ## Documentation Index
> Fetch the complete documentation index at: https://docs.node-webcodecs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# AudioData

> Represents audio sample data with format and timestamp metadata

# AudioData

The `AudioData` class represents a container for audio sample data. It provides access to raw audio samples along with metadata such as sample format, sample rate, channel count, and timestamps.

<Info>
  This API follows the [W3C WebCodecs AudioData specification](https://www.w3.org/TR/webcodecs/#audiodata-interface). Refer to the spec for detailed behavior requirements.
</Info>

<Warning>
  **Memory Management**: `AudioData` objects hold references to potentially large audio buffers. You **must** call `close()` when finished with an `AudioData` instance to release the underlying memory. Failure to do so can lead to memory leaks.
</Warning>

## Quick Example

```typescript theme={null}
import { AudioData } from 'node-webcodecs';

// Create a 1-second stereo audio buffer at 48kHz
const sampleRate = 48000;
const numberOfChannels = 2;
const numberOfFrames = sampleRate; // 1 second of audio

// Create interleaved float32 audio data
const samples = new Float32Array(numberOfFrames * numberOfChannels);

// Fill with a 440Hz sine wave
for (let i = 0; i < numberOfFrames; i++) {
  const value = Math.sin(2 * Math.PI * 440 * i / sampleRate);
  samples[i * numberOfChannels] = value;     // Left channel
  samples[i * numberOfChannels + 1] = value; // Right channel
}

const audioData = new AudioData({
  format: 'f32',
  sampleRate: sampleRate,
  numberOfFrames: numberOfFrames,
  numberOfChannels: numberOfChannels,
  timestamp: 0,
  data: samples.buffer
});

console.log(`Duration: ${audioData.duration / 1_000_000} seconds`);
console.log(`Format: ${audioData.format}`);

// Always close when done
audioData.close();
```

## Sample Formats

<Tip>
  **Planar vs Interleaved**: In **interleaved** formats, samples alternate between channels (L, R, L, R...). In **planar** formats, each channel's samples are stored contiguously in separate planes. Planar formats are often more efficient for audio processing, while interleaved formats are common for I/O operations.
</Tip>

| Format       | Description                | Bytes/Sample |
| ------------ | -------------------------- | ------------ |
| `u8`         | Unsigned 8-bit interleaved | 1            |
| `s16`        | Signed 16-bit interleaved  | 2            |
| `s32`        | Signed 32-bit interleaved  | 4            |
| `f32`        | 32-bit float interleaved   | 4            |
| `u8-planar`  | Unsigned 8-bit planar      | 1            |
| `s16-planar` | Signed 16-bit planar       | 2            |
| `s32-planar` | Signed 32-bit planar       | 4            |
| `f32-planar` | 32-bit float planar        | 4            |

## Constructor

Creates a new `AudioData` instance from the provided initialization data.

```typescript theme={null}
new AudioData(init: AudioDataInit): AudioData
```

### Parameters

<ParamField path="init" type="AudioDataInit" required>
  Configuration object for the audio data.

  <Expandable title="AudioDataInit properties">
    <ParamField path="format" type="AudioSampleFormat" required>
      The sample format of the audio data. See the sample formats table above.
    </ParamField>

    <ParamField path="sampleRate" type="number" required>
      The sample rate in Hz (e.g., 44100, 48000).
    </ParamField>

    <ParamField path="numberOfFrames" type="number" required>
      The number of audio frames. Each frame contains one sample per channel.
    </ParamField>

    <ParamField path="numberOfChannels" type="number" required>
      The number of audio channels (e.g., 1 for mono, 2 for stereo).
    </ParamField>

    <ParamField path="timestamp" type="number" required>
      The presentation timestamp in microseconds.
    </ParamField>

    <ParamField path="data" type="BufferSource" required>
      The raw audio sample data as an ArrayBuffer or TypedArray.
    </ParamField>
  </Expandable>
</ParamField>

## Properties

<ResponseField name="format" type="AudioSampleFormat | null" required>
  The sample format of the audio data. Returns `null` if the AudioData has been closed.
</ResponseField>

<ResponseField name="sampleRate" type="number" required>
  The sample rate in Hz. This value indicates how many samples represent one second of audio.
</ResponseField>

<ResponseField name="numberOfFrames" type="number" required>
  The number of audio frames in this AudioData. A frame consists of one sample per channel at a single point in time.
</ResponseField>

<ResponseField name="numberOfChannels" type="number" required>
  The number of audio channels. For example, 1 for mono audio, 2 for stereo.
</ResponseField>

<ResponseField name="duration" type="number" required>
  The duration in microseconds, calculated as `(numberOfFrames / sampleRate) * 1_000_000`.
</ResponseField>

<ResponseField name="timestamp" type="number" required>
  The presentation timestamp in microseconds, indicating when this audio should be played.
</ResponseField>

## Methods

### allocationSize()

Calculates the number of bytes needed to hold the audio data when copying with the specified options.

```typescript theme={null}
allocationSize(options: AudioDataCopyToOptions): number
```

<Accordion title="Example: Calculate buffer size">
  ```typescript theme={null}
  const audioData = new AudioData({
    format: 'f32-planar',
    sampleRate: 48000,
    numberOfFrames: 1024,
    numberOfChannels: 2,
    timestamp: 0,
    data: new Float32Array(1024 * 2).buffer
  });

  // Calculate size for first plane (channel)
  const size = audioData.allocationSize({ planeIndex: 0 });
  console.log(`Bytes needed: ${size}`); // 4096 (1024 frames * 4 bytes per f32)

  audioData.close();
  ```
</Accordion>

#### Parameters

<ParamField path="options" type="AudioDataCopyToOptions" required>
  Options specifying which portion of audio to measure.
</ParamField>

#### Returns

`number` - The number of bytes required.

***

### copyTo()

Copies audio sample data to a destination buffer.

```typescript theme={null}
copyTo(destination: BufferSource, options: AudioDataCopyToOptions): void
```

<Accordion title="Example: Copy audio data to a buffer">
  ```typescript theme={null}
  const audioData = new AudioData({
    format: 'f32-planar',
    sampleRate: 48000,
    numberOfFrames: 1024,
    numberOfChannels: 2,
    timestamp: 0,
    data: new Float32Array(1024 * 2).buffer
  });

  // Allocate destination buffer
  const size = audioData.allocationSize({ planeIndex: 0 });
  const buffer = new ArrayBuffer(size);

  // Copy first channel's data
  audioData.copyTo(buffer, { planeIndex: 0 });

  // Access as Float32Array
  const samples = new Float32Array(buffer);
  console.log(`First sample: ${samples[0]}`);

  audioData.close();
  ```
</Accordion>

<Accordion title="Example: Copy a portion of audio data">
  ```typescript theme={null}
  // Copy only 512 frames starting at frame 256
  const partialSize = audioData.allocationSize({
    planeIndex: 0,
    frameOffset: 256,
    frameCount: 512
  });

  const partialBuffer = new ArrayBuffer(partialSize);
  audioData.copyTo(partialBuffer, {
    planeIndex: 0,
    frameOffset: 256,
    frameCount: 512
  });
  ```
</Accordion>

#### Parameters

<ParamField path="destination" type="BufferSource" required>
  The destination buffer to copy audio data into. Must be large enough to hold the data.
</ParamField>

<ParamField path="options" type="AudioDataCopyToOptions" required>
  Options specifying which portion of audio to copy.
</ParamField>

#### Returns

`void`

***

### clone()

Creates a copy of this AudioData with its own data buffer.

```typescript theme={null}
clone(): AudioData
```

<Accordion title="Example: Clone audio data">
  ```typescript theme={null}
  const audioData = new AudioData({
    format: 'f32',
    sampleRate: 48000,
    numberOfFrames: 1024,
    numberOfChannels: 2,
    timestamp: 0,
    data: new Float32Array(1024 * 2).buffer
  });

  const cloned = audioData.clone();

  // Original and clone are independent
  audioData.close();

  // Clone is still valid
  console.log(`Cloned format: ${cloned.format}`);
  cloned.close();
  ```
</Accordion>

#### Returns

`AudioData` - A new AudioData instance with copied data.

***

### close()

Releases the resources held by this AudioData instance. After calling `close()`, the AudioData is no longer usable.

```typescript theme={null}
close(): void
```

<Accordion title="Example: Proper resource cleanup">
  ```typescript theme={null}
  const audioData = new AudioData({
    format: 'f32',
    sampleRate: 48000,
    numberOfFrames: 1024,
    numberOfChannels: 2,
    timestamp: 0,
    data: new Float32Array(1024 * 2).buffer
  });

  // Process audio...
  console.log(`Duration: ${audioData.duration}`);

  // Release resources when done
  audioData.close();

  // After close(), format returns null
  console.log(`Format after close: ${audioData.format}`); // null
  ```
</Accordion>

#### Returns

`void`

## Interfaces

### AudioDataInit

Configuration object passed to the `AudioData` constructor.

<ParamField path="format" type="AudioSampleFormat" required>
  The sample format of the audio data.
</ParamField>

<ParamField path="sampleRate" type="number" required>
  The sample rate in Hz.
</ParamField>

<ParamField path="numberOfFrames" type="number" required>
  The number of audio frames.
</ParamField>

<ParamField path="numberOfChannels" type="number" required>
  The number of audio channels.
</ParamField>

<ParamField path="timestamp" type="number" required>
  The presentation timestamp in microseconds.
</ParamField>

<ParamField path="data" type="BufferSource" required>
  The raw audio sample data.
</ParamField>

***

### AudioDataCopyToOptions

Options for the `allocationSize()` and `copyTo()` methods.

<ParamField path="planeIndex" type="number" required>
  The index of the plane to copy. For interleaved formats, this is always 0. For planar formats, this is the channel index.
</ParamField>

<ParamField path="frameOffset" type="number">
  The offset in frames from the start of the audio data. Defaults to 0.
</ParamField>

<ParamField path="frameCount" type="number">
  The number of frames to copy. Defaults to all remaining frames from the offset.
</ParamField>

<ParamField path="format" type="AudioSampleFormat">
  Optional target format for conversion during copy. If not specified, uses the source format.
</ParamField>

## Type Aliases

### AudioSampleFormat

```typescript theme={null}
type AudioSampleFormat =
  | "u8"
  | "s16"
  | "s32"
  | "f32"
  | "u8-planar"
  | "s16-planar"
  | "s32-planar"
  | "f32-planar";
```

## See Also

<CardGroup cols={3}>
  <Card title="AudioEncoder" icon="compress" href="/api-reference/AudioEncoder">
    Encode raw audio data into compressed formats
  </Card>

  <Card title="AudioDecoder" icon="expand" href="/api-reference/AudioDecoder">
    Decode compressed audio into AudioData
  </Card>

  <Card title="EncodedAudioChunk" icon="box" href="/api-reference/EncodedAudioChunk">
    Container for encoded audio data
  </Card>
</CardGroup>
