萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 結合 FFmpeg 與 Mencoder 實現影片轉 MP4 並擷取預覽圖

前言

在 Web 專案中常需將上傳的影片轉碼為通用的 MP4 格式,並產生縮圖作為預覽。本文展示如何在 PHP 中呼叫 FFmpeg 與 Mencoder 兩大多媒體工具,完成影片轉碼與縮圖擷取。

環境需求

  • 伺服器已安裝 ffmpeg 與 mencoder 並加入系統 PATH。
  • PHP 可執行 shell_exec() 或 exec()(需確認 disable_functions 未禁用)。
  • 具備足磁碟空間與 CPU 資源,影片轉碼屬高負載運算。

核心函數實作

<?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

最佳實務建議

  1. 非同步處理:轉碼耗時長,應放入工作佇列(如 Redis + Worker、Gearman、Laravel Queue)背景執行,避免阻塞 HTTP 請求。
  2. 路徑安全:所有輸入路徑務必經 escapeshellarg() 處理,防止指令注入。
  3. 錯誤捕捉:檢查 shell_exec 回傳值與 $?} 狀態碼,失敗時記錄完整指令與錯誤輸出。
  4. 現代替代方案:新專案建議改用 ffmpeg 單一工具完成轉碼與縮圖(支援 libx264、libmp3lame),指令更統一、維護性更高。
copyright © 萬盛學電腦網 all rights reserved