首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 使用 MEncoder 轉換影片為 MP4:shell_exec 整合 FFmpeg/MEncoder 指令

     編輯:PHP 相關知識

前言

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";
}
?>

關鍵安全措施

  • escapeshellarg():必須對所有使用者輸入參數使用,防止命令注入。
  • 路徑驗證:確保輸入/輸出路徑在允許目錄內(realpath() 比對)。
  • 停用危險函數:php.ini 設定 disable_functions=shell_exec,exec,system,passthru,若需用請限制於特定 CLI 腳本。

非同步處理架構(生產環境推薦)

// 1. Web 請求:儲存檔案 → 寫入任務佇列 (Redis/RabbitMQ/Database) → 立即回應
// 2. Worker 進程:監聽佇列 → 呼叫 ffmpeg/mencoder → 更新狀態 → 通知前端 (WebSocket/推播)
// 3. 前端:輪詢或 WebSocket 顯示進度
?>

FFmpeg 替代方案(更現代、支援 MP4 直接輸出)

<?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 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved