PHP通过shell_exec等函数调用已安装的FFmpeg将视频转WebM,需先验证ffmpeg -version及PATH配置,再用escapeshellarg安全执行-vp9+opus编码命令,并建议proc_open捕获错误。

PHP 本身不直接处理视频编码,但可以通过 执行系统命令 调用 FFmpeg 将视频转为 WebM 格式。关键在于确保服务器已安装 FFmpeg,且 PHP 有权限运行外部命令(如 exec、shell_exec)。
确认 FFmpeg 已正确安装并可用
在终端中运行以下命令验证:
ffmpeg -version
若提示“command not found”,需先安装 FFmpeg(Ubuntu/Debian:`sudo apt install ffmpeg`;CentOS/RHEL:`sudo yum install epel-release && sudo yum install ffmpeg`;macOS:`brew install ffmpeg`)。
PHP 中可简单检测:
立即学习“PHP免费学习笔记(深入)”;
$output = shell_exec('which ffmpeg 2>&1');
if (empty($output)) {
die('FFmpeg 未找到,请检查安装和 PATH 配置');
}
基础转码命令(推荐 VP9 + Opus)
WebM 容器通常使用 VP9 视频编码和 Opus 音频编码,兼顾质量与兼容性。PHP 中调用示例如下:
$input = '/path/to/input.mp4';
$output = '/path/to/output.webm';
$cmd = sprintf(
'ffmpeg -i %s -c:v libvpx-vp9 -c:a libopus -b:v 1000k -b:a 128k -threads 4 -y %s 2>&1',
escapeshellarg($input),
escapeshellarg($output)
);
$result = shell_exec($cmd);
// 检查 $result 是否含 error 或 ffmpeg 输出日志
-
-c:v libvpx-vp9:指定 VP9 编码器(现代 WebM 推荐) -
-c:a libopus:Opus 音频更小、音质更好,比 Vorbis 更优 -
-b:v 1000k和-b:a 128k:可按需调整码率(如移动端可降为 600k/64k) -
escapeshellarg()必须使用,防止路径含空格或特殊字符引发命令注入或失败 -
-y自动确认覆盖输出文件
添加错误处理与进度监控(可选进阶)
生产环境建议捕获错误并限制执行时间:
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
$process = proc_open(
$cmd,
$descriptors,
$pipes,
dirname($input),
[]
);
if (!is_resource($process)) {
die('无法启动 FFmpeg 进程');
}
// 读取 stderr 实时判断是否失败(如编码器不支持、文件损坏)
stream_set_blocking($pipes[2], false);
$errorOutput = stream_get_contents($pipes[2]);
proc_close($process);
if (stripos($errorOutput, 'Error') !== false || stripos($errorOutput, 'failed') !== false) {
error_log("FFmpeg 错误: $errorOutput");
// 可记录日志或返回用户友好提示
}
替代方案:使用 FFmpeg-PHP 扩展(已过时,不推荐)
旧版 ffmpeg-php 扩展早已停止维护,且不支持 PHP 7+ 和现代 FFmpeg API,切勿在新项目中使用。坚持走 shell 调用路线更稳定、可控、易调试。



















