Skip to content

Instantly share code, notes, and snippets.

@Elements-
Created March 26, 2016 18:32
Show Gist options
  • Save Elements-/cf063254730cd754599e to your computer and use it in GitHub Desktop.
Save Elements-/cf063254730cd754599e to your computer and use it in GitHub Desktop.
Read the duration of a mp4 file nodejs
var buff = new Buffer(100);
fs.open(file, 'r', function(err, fd) {
fs.read(fd, buff, 0, 100, 0, function(err, bytesRead, buffer) {
var start = buffer.indexOf(new Buffer('mvhd')) + 17;
var timeScale = buffer.readUInt32BE(start, 4);
var duration = buffer.readUInt32BE(start + 4, 4);
var movieLength = Math.floor(duration/timeScale);
console.log('time scale: ' + timeScale);
console.log('duration: ' + duration);
console.log('movie length: ' + movieLength + ' seconds');
});
});
@pundoo
Copy link

pundoo commented Sep 8, 2021

Adding on @numToStr

I ran into some files having mvhd header towards the end (ish). In that case..

const { size } = await fs.stat("video.mp4");
const buff = Buffer.alloc(size);
const { buffer } = await file.read(buff, 0, size, 0);

@redsuperbat
Copy link

redsuperbat commented Apr 25, 2023

The first post has the wrong offset for the start variable. It should be +16 not +17.

This is my updated gist:

  const buf = Buffer.alloc(100);
  const file = await fs.open(resource);
  const { buffer } = await file.read({
    buffer: buf,
    length: 100,
    offset: 0,
    position: 0,
  });
  await file.close();
  
  const start = buffer.indexOf(Buffer.from("mvhd")) + 16;
  const timeScale = buffer.readUInt32BE(start);
  const duration = buffer.readUInt32BE(start + 4);
  const movieLength = Math.floor(duration / timeScale);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment