4

How do you get/calculate the duration/length of an mp4 video with php?

I tried using this but it only works for f4v. :< Can you help me with the mp4 case ?

Reno
  • 33,594
  • 11
  • 89
  • 102
John
  • 41
  • 1
  • 2

3 Answers3

4

I could not get tandu's solution working.

Here's what eventually worked for me:

$ffmpeg_output = shell_exec("ffmpeg -i \"$file\" 2>&1");
if( preg_match('/.*Duration: ([0-9:]+).*/', $ffmpeg_output, $matches) ) {
    echo $matches[1];
} else {
    echo "$file failed\n";
}

Hope this helps someone.

Henno
  • 1,448
  • 4
  • 18
  • 30
  • Simple and perfect. Thanks for posting @Henno – Radhakrishna Sep 08 '15 at 06:37
  • This can result in 0 second durations. As ffmpeg will also return milliseconds. So the output is like this: **00:00:05.66** and the regex above will ignore decimal **00:00:05**. What you need is: `/.*Duration: ((\d+)(?:\:)(\d+)(?:\:)(\d+))*/i`. – Kalle H. Väravas Sep 22 '17 at 20:28
2

I've also wanted to do this recently. I did a lot of research on it, and there is no native way in php. One suggestion is ffmpeg-php, but it did not appear to work for me. Another method is to use the command line ffmpeg:

exec("ffmpeg -i \"{$videofile}\" 2>&1");
$search='/Duration: (.*?),/';
$duration=preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE, 3);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • I created a php class based on this approach: https://github.com/bfanger/sledgehammer_ffmpeg/blob/master/classes/FFVideo.php – Bob Fanger Feb 12 '11 at 09:33
1

This can be done in pure php by using the php-reader library. This library is a full implementation of the ISO Base Media File Format, or ISO/IEC 14496-12 in pure php. Then you can either trust the metadata header for the duration, or calculate it yourself based on the stbl boxes.

Jon Skarpeteig
  • 4,118
  • 7
  • 34
  • 53