在 Web 專案中常需將上傳的影片轉碼為通用的 MP4 格式,並產生縮圖作為預覽。本文展示如何在 PHP 中呼叫 FFmpeg 與 Mencoder 兩大多媒體工具,完成影片轉碼與縮圖擷取。
ffmpeg 與 mencoder 並加入系統 PATH。shell_exec() 或 exec()(需確認 disable_functions 未禁用)。<?php
/**
* 影片轉 MP4 並擷取縮圖
*
* @param string $in 輸入影片路徑
* @param string $out_thumb 輸出縮圖路徑 (JPG)
* @param string $out_vid 輸出影片路徑 (MP4/OGM)
*/
function flv_convert_get_thumb($in, $out_thumb, $out_vid) {
// 1. 擷取縮圖:第 5 秒、1 幀、286x160、16:9
$cmdThumb = sprintf(
'ffmpeg -v 0 -y -i %s -vframes 1 -ss 5 -vcodec mjpeg -f rawvideo -s 286x160 -aspect 16:9 %s',
escapeshellarg($in),
escapeshellarg($out_thumb)
);
shell_exec($cmdThumb);
// 2. 轉碼為 MP4 (使用 mencoder + x264 + mp3lame)
$cmdVideo = sprintf(
'mencoder %s -o %s -af volume=10 -aspect 16:9 -of avi -noodml -ovc x264 -x264encopts bitrate=500:level_idc=41:bframes=3:frameref=2:nopsnr:nossim:pass=1:threads=auto -oac mp3lame',
escapeshellarg($in),
escapeshellarg($out_vid)
);
shell_exec($cmdVideo);
}
// 使用範例
flv_convert_get_thumb('input.avi', 'output.jpg', 'output.mp4');
?>
| 參數 | 說明 |
|---|---|
| -vframes 1 | 只擷取 1 幀畫面 |
| -ss 5 | 跳到第 5 秒位置 |
| -s 286x160 | 縮圖解析度 |
| -ovc x264 | 視訊編碼器 H.264 |
| -x264encopts ... | x264 進階參數:碼率 500kbps、Level 4.1、B幀 3、參考幀 2、單通道、自動執行緒 |
| -oac mp3lame | 音訊編碼 MP3 |
escapeshellarg() 處理,防止指令注入。shell_exec 回傳值與 $?} 狀態碼,失敗時記錄完整指令與錯誤輸出。ffmpeg 單一工具完成轉碼與縮圖(支援 libx264、libmp3lame),指令更統一、維護性更高。