Opus Encoder
Since the AudioEncoder
API is currently only supported on Chromium-based browsers, we have implemented a replacement using an Emscripten-compiled version of libopus. In this guide, we will use an audio buffer generated with the Web Audio API and multiplex it into an MP4 container using mp4-muxer.
Basic Setup
Start by creating a new Muxer
instance:
Next, create an Opus encoder instance and use the encoder callback to pass audio chunks directly into the muxer:
Configuring the Encoder
The encoder configuration is asynchronous, as the WASM file is fetched if it isn't cached. Configure the encoder as shown below:
Preparing Audio Samples for Encoding
To create an audio buffer, we’ll use the Fetch API and the Web Audio API. Here's an example that fetches and decodes an MP3 file:
Since the encoder works with interleaved Int16
samples, we need to convert the AudioBuffer
. Diffusion Studio provides a utility for this:
Encoding Audio Samples
Now, pass the prepared samples to the encoder for processing:
The numberOfFrames
parameter refers to the number of audio samples per channel.
Finalizing the Muxer and Exporting the MP4
Once encoding is complete, finalize the muxer and extract the MP4 file:
You now have an MP4 file that contains your encoded Opus audio.