PHP 本身不處理影片編碼,透過 shell_exec() 呼叫系統安裝的 mencoder 或 ffmpeg 完成轉碼。本文示範基本整合、參數解析、安全與非同步處理建議。
<?php
function convertToMp4(string $input, string $output): bool {
// 檢查輸入檔案
if (!file_exists($input)) {
throw new \InvalidArgumentException("輸入檔案不存在: $input");
}
// MEncoder 指令參數說明:
// -af volume=10 音量增益
// -aspect 16:9 寬高比
// -of avi 輸出容器格式 (此處輸出 avi,再由 ffmpeg 轉 mp4 較佳)
// -ovc x264 視訊編碼器 H.264
// -x264encopts ... x264 詳細參數
// -oac mp3lame 音訊編碼器 MP3
$cmd = 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($input),
escapeshellarg($output)
);
echo "執行指令: $cmd\n";
$result = shell_exec($cmd);
// 簡易判斷:檢查輸出檔案是否存在且大小 > 0
return file_exists($output) && filesize($output) > 0;
}
// 使用
try {
if (convertToMp4('input.avi', 'output.mp4')) {
echo "轉碼成功\n";
} else {
echo "轉碼失敗\n";
}
} catch (\Exception $e) {
echo "錯誤: " . $e->getMessage() . "\n";
}
?>
realpath() 比對)。php.ini 設定 disable_functions=shell_exec,exec,system,passthru,若需用請限制於特定 CLI 腳本。// 1. Web 請求:儲存檔案 → 寫入任務佇列 (Redis/RabbitMQ/Database) → 立即回應
// 2. Worker 進程:監聽佇列 → 呼叫 ffmpeg/mencoder → 更新狀態 → 通知前端 (WebSocket/推播)
// 3. 前端:輪詢或 WebSocket 顯示進度
?>
<?php
function convertWithFFmpeg(string $input, string $output): bool {
$cmd = sprintf(
'ffmpeg -y -i %s -c:v libx264 -preset medium -crf 23 -c:a aac -b:a 128k %s',
escapeshellarg($input),
escapeshellarg($output)
);
$result = shell_exec($cmd);
return file_exists($output) && filesize($output) > 0;
}
?>
FFmpeg 直接支援 MP4 容器,參數更直觀,建議優先使用。
PHP 整合影片轉碼核心為 shell_exec + escapeshellarg。生產環境必須採用非同步佇列架構,避免阻塞 Web 請求、超時、資源耗盡。希望本文對您的 PHP 程式設計有所幫助。