PHP 7 FFMPEG Script to Generate Youtube Video Thumbnail For Preview in Browser Full Project For Beginners

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

 

 

 

index.php

 

 

$video_path = 'path/to/example_preview/input.mp4';

$dur = shell_exec("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 '$video_path'");
$seconds = round($dur);

$thumb_0 = gmdate('H:i:s', $seconds / 8);
$thumb_1 = gmdate('H:i:s', $seconds / 4);
$thumb_2 = gmdate('H:i:s', $seconds / 2 + $seconds / 8);
$thumb_3 = gmdate('H:i:s', $seconds / 2 + $seconds / 4);

$path_clip = 'path/to/example_preview/;

$preview_list = fopen($path_clip . 'list.txt', "w");
$preview_array = [];

for ($i=0; $i <= 3; $i++) {
  $thumb = ${'thumb_'.$i};
  shell_exec("ffmpeg -i '$video_path' -an -ss $thumb -t 2 -vf 'scale=320:180:force_original_aspect_ratio=decrease,pad=320:180:(ow-iw)/2:(oh-ih)/2,setsar=1' -y $path_clip/$i.p.mp4");

  $output = $path_clip . $i.'.p.mp4';

  if (file_exists($output)) {
    fwrite($preview_list, "file '". $output . "'\n");
    array_push($preview_array, $output);
  }
}

fclose($preview_list);

shell_exec("ffmpeg -f concat -safe 0 -i $path_clip/list.txt -y $path_clip/preview.mp4");

if (!empty($preview_array)) {
  foreach ($preview_array as $v) {
    unlink($v);
  }
}

// remove preview list
unlink($path_clip . 'list.txt');

Leave a Reply