透過 PHP 呼叫系統指令 ffmpeg,可擷取影片指定時間點的縮圖,並解析影片總長度與建立時間。需確認伺服器已安裝 FFmpeg 且 PHP 有 exec()/system() 執行權限。
<?php
function getVideoCover($file, $time, $name) {
if (empty($time)) $time = '1'; // 預設第 1 秒
// ffmpeg -i 輸入檔 -y -f mjpeg -ss 起始秒 -t 持續秒 -s 尺寸 輸出檔
$cmd = "ffmpeg -i {$file} -y -f mjpeg -ss 3 -t {$time} -s 320x240 {$name}";
$result = system($cmd);
return $result;
}
?>
參數說明:-ss 指定開始時間,-t 指定擷取時長,-s 設定輸出解析度。
<?php
function getTime($file) {
// 解析 ffmpeg 輸出中的 Duration 欄位
$vtime = exec("ffmpeg -i {$file} 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//");
$ctime = date('Y-m-d H:i:s', filectime($file));
return array('vtime' => $vtime, 'ctime' => $ctime);
}
?>
回傳陣列包含 vtime(格式如 00:04:32.00)與 ctime(檔案建立時間)。
<?php
list($h, $m, $s) = explode(':', $vtime);
$totalSeconds = $h * 3600 + $m * 60 + round($s);
?>
escapeshellarg() 或 escapeshellcmd() 防止指令注入。