Use this file to discover all available pages before exploring further.
Mediabunny enables you to create media files with fine-grained control. You can add multiple video, audio, and subtitle tracks to a media file and precisely control the timing of media data.Using output targets, you can decide whether to build the entire file in memory or stream it out in chunks as it’s being created, allowing you to create very large files efficiently.
Media file creation in Mediabunny revolves around the Output class. One instance of Output represents one media file you want to create.
1
Import the required classes
import { Output, Mp4OutputFormat, BufferTarget } from 'mediabunny';
2
Create a new output
const output = new Output({ format: new Mp4OutputFormat(), target: new BufferTarget(),});
The format determines the container format of the output file (MP4, WebM, etc.).The target determines where the data will be written (memory, disk, stream, etc.). See the Streaming guide for available targets.
output.addVideoTrack(videoSource, { // Clockwise rotation in degrees rotation: 90, // Expected frame rate in hertz frameRate: 30, // ISO 639-2/T language code language: 'eng', // User-defined track name name: 'Main camera', // Track disposition flags disposition: { default: true },});
The frameRate option snaps all timestamps and durations to the specified frame rate. To achieve fractional frame rates precisely, use their exact fractional forms:
After starting an output, use the media sources to pipe data to the output file:
// For a CanvasSource, capture frames at regular intervalslet framesAdded = 0;const intervalId = setInterval(() => { const timestamp = framesAdded / 30; const duration = 1 / 30; // Captures the canvas state at the time of calling add videoSource.add(timestamp, duration); framesAdded++;}, 1000 / 30);// Audio from MediaStreamAudioTrackSource is automatically piped// after calling start()
The API differs for each media source type - check the media sources documentation for details.
This promise only resolves once codec strings for all tracks are known, which requires encoders to be initialized. Don’t await this before adding media data or you’ll create a deadlock.
Some output formats require packet buffering for multi-track outputs. The output must wait for data from all tracks for a given timestamp before writing.
To minimize memory usage, add media data in an interleaved way. For example, add 10 seconds of video, then 10 seconds of audio, then repeat - instead of adding all video first, then all audio.