php 7.4 本身不支持视频转 hls,需调用 ffmpeg 命令生成 .m3u8 和 .ts 文件;关键在于验证 ffmpeg 是否支持 hls muxer、使用 escapeshellarg 防注入、proc_open 捕获错误,并确保 web 服务器配置正确 mime 类型。

PHP 7.4 本身不直接支持视频转 HLS,它需要调用外部命令行工具 ffmpeg 来完成。关键在于:确保系统已安装正确版本的 ffmpeg,并通过 PHP 的 exec、shell_exec 或 proc_open 安全地调用它生成 HLS(即 .m3u8 + .ts 文件)。
确认 ffmpeg 已安装并支持 HLS
在终端运行以下命令验证:
ffmpeg -version ffmpeg -h muxer=hls
如果看到 hls muxer 相关信息,说明支持。若提示“Unknown muxer 'hls'”,说明编译时未启用 libx264、libx265 或 fdk-aac 等依赖,需重装官方静态版(推荐从 ffmpeg.org 下载)或用包管理器安装完整版(如 Ubuntu 上:sudo apt install ffmpeg)。
基础 HLS 转码命令(PHP 中可直接调用)
以下命令将输入视频转为自适应多清晰度 HLS(含 master.m3u8),适用于大多数场景:
- 使用 H.264 编码、AAC 音频,分片 10 秒,生成 360p/720p 两档清晰度
- 输出到
hls_output/目录,包含master.m3u8和对应 ts 分片
命令示例:
ffmpeg -i input.mp4 \ -profile:v baseline -level 3.0 \ -s 640x360 -c:v libx264 -b:v 800k -keyint_min 60 -g 60 -sc_threshold 0 -c:a aac -b:a 96k -ar 44100 -hls_time 10 -hls_playlist_type vod -hls_segment_filename "hls_output/360p_%05d.ts" hls_output/360p.m3u8 \ -s 1280x720 -c:v libx264 -b:v 2800k -keyint_min 60 -g 60 -sc_threshold 0 -c:a aac -b:a 128k -ar 44100 -hls_time 10 -hls_playlist_type vod -hls_segment_filename "hls_output/720p_%05d.ts" hls_output/720p.m3u8 \ -y -f hls -hls_master_pl_name master.m3u8 hls_output/master.m3u8
PHP 7.4 中安全执行(推荐用 proc_open)
避免 shell 注入,不要拼接用户输入进命令。建议只处理服务端已知路径的文件:
$inputPath = '/var/www/videos/source.mp4';
$outputDir = '/var/www/hls/20241125/';
$cmd = "ffmpeg -i " . escapeshellarg($inputPath) . " -c:v libx264 -c:a aac -hls_time 10 -hls_playlist_type vod -hls_segment_filename " . escapeshellarg($outputDir . "seg_%05d.ts") . " -y " . escapeshellarg($outputDir . "playlist.m3u8");
$descriptorspec = [
0 => ["pipe", "r"],
1 => ["pipe", "w"],
2 => ["pipe", "w"]
];
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$returnCode = proc_close($process);
if ($returnCode === 0) {
echo "HLS 生成成功,播放地址:/hls/20241125/playlist.m3u8";
} else {
error_log("FFmpeg 错误:$stderr");
echo "转码失败,请检查日志";
}
}
注意事项与常见问题
- 权限问题:PHP 进程(如 www-data)需对输入目录有读取权、输出目录有写入权
-
超时限制:大视频可能超时,设置
set_time_limit(0)并考虑异步处理(如队列+后台进程) -
HLS 播放要求:Web 服务器需支持
.m3u8和.ts的 MIME 类型(Nginx 添加:types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; }) - HTTPS 适配:若站点启用了 HTTPS,确保所有 ts 文件 URL 也是 https,否则浏览器会拦截混合内容
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











