The AudioDecoder class decodes compressed audio data (EncodedAudioChunk) into raw audio samples (AudioData). It supports common audio codecs like AAC, MP3, Opus, and FLAC.
import { AudioDecoder, EncodedAudioChunk } from 'node-webcodecs';// Create decoder with callbacksconst decoder = new AudioDecoder({ output: (audioData) => { console.log(`Decoded ${audioData.numberOfFrames} samples`); console.log(`Format: ${audioData.format}, Rate: ${audioData.sampleRate}Hz`); // Process the audio data... // IMPORTANT: Always close AudioData when done audioData.close(); }, error: (e) => console.error('Decode error:', e)});// Configure for AAC decodingdecoder.configure({ codec: 'mp4a.40.2', // AAC-LC sampleRate: 48000, numberOfChannels: 2});// Decode encoded chunksconst chunk = new EncodedAudioChunk({ type: 'key', timestamp: 0, data: aacFrameData});decoder.decode(chunk);// Flush remaining data when doneawait decoder.flush();decoder.close();
Always call audioData.close() in your output callback after processing. AudioData objects hold native memory that JavaScript’s garbage collector cannot reclaim automatically. Failing to close them will cause memory leaks.
Callback invoked for each decoded audio frame. The AudioData object contains
raw PCM samples ready for playback or processing. You must call audioData.close()
when finished with each frame.
Number of chunks waiting to be decoded. Use this for backpressure management -
if the queue grows too large, pause feeding new chunks until it decreases.
// For AAC from MP4 container, you may need the AudioSpecificConfigconst audioSpecificConfig = new Uint8Array([0x11, 0x90]); // Example for 48kHz stereo AAC-LCdecoder.configure({ codec: 'mp4a.40.2', sampleRate: 48000, numberOfChannels: 2, description: audioSpecificConfig});
The encoded audio chunk to decode. Unlike video, most audio chunks are keyframes
and can be decoded independently.
Throws:
InvalidStateError if the decoder is not configured
DataError if the chunk data is malformed
Example: Decode audio stream
Copy
import { AudioDecoder, EncodedAudioChunk } from 'node-webcodecs';// Assuming you have an array of AAC frames from a parserconst aacFrames: Uint8Array[] = parseAACStream(audioData);for (let i = 0; i < aacFrames.length; i++) { const chunk = new EncodedAudioChunk({ type: 'key', // Audio frames are typically keyframes timestamp: i * 21333, // ~21ms per AAC frame at 48kHz duration: 21333, data: aacFrames[i] }); decoder.decode(chunk);}