php 实现 rtmp
PHP 实现 RTMP 推流/拉流
PHP 本身不直接支持 RTMP 协议处理,但可以通过调用外部工具或扩展库实现 RTMP 功能。以下是几种常见方法:
调用 FFmpeg 实现 RTMP 推流
通过 PHP 执行 FFmpeg 命令将本地视频文件或摄像头流推送到 RTMP 服务器:
$ffmpegPath = '/usr/bin/ffmpeg';
$inputFile = 'input.mp4';
$rtmpUrl = 'rtmp://example.com/live/streamkey';
$command = "$ffmpegPath -re -i $inputFile -c:v libx264 -preset veryfast -maxrate 3000k -bufsize 6000k -pix_fmt yuv420p -g 50 -c:a aac -b:a 160k -ac 2 -ar 44100 -f flv $rtmpUrl";
exec($command);
使用 PHP-FFmpeg 扩展库
安装 PHP-FFmpeg 库后可以通过面向对象方式操作:
require 'vendor/autoload.php';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('input.mp4');
$video->save(new FFMpeg\Format\Video\FLV(), 'rtmp://example.com/live/streamkey');
通过 SRS 等 RTMP 服务器实现
配置 SRS/nginx-rtmp 等服务器后,PHP 可通过 HTTP API 控制流:
$apiUrl = 'http://rtmp-server:1985/api/v1/streams';
$data = ['action' => 'publish', 'stream' => 'test'];
file_get_contents($apiUrl.'?'.http_build_query($data));
RTMP 拉流处理
使用 FFmpeg 将 RTMP 流转换为其他格式或保存:
$command = 'ffmpeg -i rtmp://example.com/live/streamkey -c copy -f mp4 output.mp4';
shell_exec($command);
注意事项
- 服务器需安装 FFmpeg 并支持 RTMP 协议
- 推流过程会持续占用进程,建议使用后台任务或 supervisor 管理
- 考虑使用 WebSocket+RTMP 组合实现网页播放器
- 直播场景需处理断流重连和缓冲机制
性能优化建议
对于高并发场景,建议采用以下架构:

- 使用 nginx-rtmp 或 SRS 作为流媒体服务器
- PHP 只负责业务逻辑和控制接口
- 前端通过 HLS 或 HTTP-FLV 协议播放
- 考虑使用 CDN 分发直播流






