在視頻平台、教學系統、內容審核等場景,常需對上傳視頻自動生成縮略圖、燒錄字幕、轉碼為統一格式。本文提供一套基於 PHP shell_exec 調用 FFmpeg/MEncoder 的完整方案,涵蓋批量處理、參數優化與錯誤容錯。
exec、shell_exec 函數,且 Web 用戶對二進制文件有執行權限<?php
$dir = __DIR__ . '/videos/';
$allowedExt = ['avi', 'mp4', 'mkv', 'mov'];
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
$path = $dir . $file;
if (!is_file($path)) continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt)) continue;
$base = $dir . pathinfo($file, PATHINFO_FILENAME);
$subFile = $base . '.srt'; // 字幕文件
$idxFile = $base . '.idx'; // VobSub 索引(可選)
$thumbFile = $base . '.jpg'; // 縮略圖
$outFile = $base . '.mp4'; // 輸出文件
if (file_exists($subFile)) {
processVideo($path, $subFile, $idxFile, $thumbFile, $outFile);
} else {
error_log("字幕缺失:$subFile");
}
}
closedir($handle);
}
function processVideo($in, $sub, $idx, $thumb, $out) {
// 1. 提取縮略圖(第 250 幀,16:9,286x160)
$cmd = "ffmpeg -v 0 -y -i " . escapeshellarg($in) .
" -vframes 1 -ss 250 -vcodec mjpeg -f rawvideo -s 286x160 -aspect 16:9 " .
escapeshellarg($thumb);
$res = shell_exec($cmd);
if ($res === null || !file_exists($thumb)) {
error_log("縮略圖生成失敗:$in");
}
// 2. 燒錄字幕並轉碼(H.264 + AVI 容器)
$cmd = "mencoder " . escapeshellarg($in) .
" -o " . escapeshellarg($out) .
" -sub " . escapeshellarg($sub) .
" -subfont-text-scale 3.0 -subpos 99 " .
" -af volume=10 -aspect 16:9 -of avi -noodml " .
" -ovc x264 -x264encopts bitrate=1200:threads=auto " .
" -oac mp3lame -lameopts vbr=3:br=128";
$res = shell_exec($cmd);
if ($res === null || !file_exists($out)) {
error_log("視頻轉碼失敗:$in");
}
}
| 參數 | 含義 | 調優建議 |
|---|---|---|
-ss 250 | 跳轉至第 250 幀提取縮略圖 | 根據視頻時長動態計算,避免黑幀 |
-subfont-text-scale 3.0 | 字幕字體縮放比例 | 高清視頻建議 3.0-4.0,標清 2.0 |
-subpos 99 | 字幕垂直位置(0-100) | 99 靠近底部,避免遮擋畫面 |
-af volume=10 | 音頻增益 10dB | 視源音量調整,防止炸音 |
-x264encopts bitrate=1200 | H.264 目標碼率 kbps | 720p 建議 1500-2500,1080p 4000+ |
threads=auto | 自動使用所有 CPU 核心 | 生產環境可指定具體核心數 |
-progress 輸出,實時寫入數據庫,前端輪詢展示進度條。escapeshellarg() 轉義,防止命令注入。tmpwatch 或 cron 任務。ffmpeg-php 或 php-ffmpeg 等擴展替代 shell_exec,獲得更好的錯誤處理與面向對象介面。通過 PHP 調用 FFmpeg/MEncoder 組合,可快速構建視頻字幕燒錄、縮略圖生成、格式統一轉碼的自動化流水線。掌握核心參數含義並引入異步隊列、進度監控,即可支撐中小型視頻業務的日常處理需求。