The AudioEncoder class encodes raw AudioData objects into compressed EncodedAudioChunk objects. It supports common audio codecs like AAC, MP3, Opus, FLAC, and Vorbis through FFmpeg.
import { AudioEncoder, AudioData } from 'node-webcodecs';// Create an AAC encoderconst encoder = new AudioEncoder({ output: (chunk, metadata) => { console.log(`Encoded ${chunk.byteLength} bytes at ${chunk.timestamp}μs`); // First chunk includes decoder config if (metadata?.decoderConfig) { console.log('Decoder config:', metadata.decoderConfig); } }, error: (err) => console.error('Encoding error:', err)});// Configure for AAC-LC at 128kbpsencoder.configure({ codec: 'mp4a.40.2', // AAC-LC sampleRate: 48000, numberOfChannels: 2, bitrate: 128_000});// Create audio data from raw samplesconst audioData = new AudioData({ format: 'f32-planar', sampleRate: 48000, numberOfFrames: 1024, numberOfChannels: 2, timestamp: 0, data: audioSamples});// Encode and close the source dataencoder.encode(audioData);audioData.close(); // Important: prevent memory leaks// Wait for encoding to completeawait encoder.flush();encoder.close();
Always call audioData.close() after passing it to encode(). Failing to close AudioData objects will cause memory leaks as the underlying buffers are not automatically released.
Wait for all pending encode operations to complete.
Copy
flush(): Promise<void>
Returns:Promise<void> - Resolves when all queued audio data has been encoded.Throws:
InvalidStateError if encoder is not configured
Rejects if encoding fails
Example: Flushing the encoder
Copy
// Encode all audio datafor (const frame of audioFrames) { encoder.encode(frame); frame.close();}// Wait for all encoding to completeawait encoder.flush();console.log('All audio encoded!');// Now safe to closeencoder.close();
Aborts all pending encode operations and resets to the 'unconfigured' state.
You must call configure() again before encoding more audio.Throws:InvalidStateError if encoder is closed
Example: Resetting and reconfiguring
Copy
encoder.configure({ codec: 'mp4a.40.2', sampleRate: 48000, numberOfChannels: 2});encoder.encode(audioData);// Abort and reconfigure with different settingsencoder.reset();encoder.configure({ codec: 'opus', sampleRate: 48000, numberOfChannels: 2});
The encoder cannot be used after calling close(). Any pending encode operations
are aborted and the state transitions to 'closed'.
Example: Proper cleanup
Copy
// Encode all audiofor (const frame of audioFrames) { encoder.encode(frame); frame.close();}// Wait for encoding to completeawait encoder.flush();// Release resourcesencoder.close();// encoder.encode() will now throw InvalidStateError