MP4Box.js

2.3.0 · active · verified Tue Apr 21

MP4Box.js is a robust JavaScript library designed for comprehensive processing of MP4 files, including parsing, segmentation, and sample extraction. It enables advanced functionalities directly within web browsers or Node.js environments, making it a critical tool for working with the Media Source Extensions (MSE) API for adaptive streaming. The current stable version is 2.3.0, with a history of frequent minor and patch releases, indicating active development and maintenance. Key differentiators include its progressive parsing capabilities, cross-platform support, and its direct inspiration from the well-established GPAC MP4Box tool, providing a powerful and familiar API for developers handling MP4 media.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to progressively parse an MP4 file by fetching data chunks and appending them to an `MP4File` instance. It sets up `onMoovStart` and `onReady` callbacks to log file metadata as it becomes available. The example fetches a small MP4 from GitHub to simulate real-world usage.

import MP4Box from 'mp4box';

const mp4boxfile = MP4Box.createFile();
mp4boxfile.onError = function(e) {
  console.error('MP4Box error:', e);
};
mp4boxfile.onMoovStart = function () {
  console.log('Starting to receive File Information (moov box)');
};
mp4boxfile.onReady = function(info) {
  console.log('Received File Information:', info);
  // Example: Log track details
  info.tracks.forEach(track => {
    console.log(`Track ID: ${track.id}, Type: ${track.movie_type}, Codec: ${track.codec}, Duration: ${track.duration/track.timescale}s`);
  });
};

// Simulate appending data (e.g., from a fetched MP4 file)
async function loadMp4Data() {
  // In a real scenario, 'url' would be the path to your MP4 file
  const url = 'https://raw.githubusercontent.com/gpac/mp4box.js/master/test/initial-media/mp4/frag_raw.mp4';
  const response = await fetch(url);
  const reader = response.body.getReader();
  let offset = 0;
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      mp4boxfile.flush(); // Signal end of file
      break;
    }
    const buffer = value.buffer; // value is a Uint8Array, get its underlying ArrayBuffer
    buffer.fileStart = offset; // Important for MP4Box to track byte ranges
    mp4boxfile.appendBuffer(buffer);
    offset += buffer.byteLength;
  }
}

loadMp4Data();

view raw JSON →