php 实现 rtmp
RTMP 协议简介
RTMP(Real-Time Messaging Protocol)是Adobe开发的实时消息传输协议,常用于直播和视频流传输。PHP本身不直接支持RTMP协议,但可以通过扩展或调用外部工具实现相关功能。
使用FFmpeg处理RTMP流
FFmpeg是一个开源的多媒体处理工具,支持RTMP协议的推流和拉流操作。PHP可以通过exec()或shell_exec()调用FFmpeg命令。
推流到RTMP服务器示例:
$ffmpegPath = '/usr/bin/ffmpeg';
$inputFile = 'input.mp4';
$rtmpUrl = 'rtmp://example.com/live/streamkey';
$command = "$ffmpegPath -re -i $inputFile -c:v libx264 -preset ultrafast -tune zerolatency -c:a aac -f flv $rtmpUrl";
exec($command);
从RTMP服务器拉流示例:
$ffmpegPath = '/usr/bin/ffmpeg';
$rtmpUrl = 'rtmp://example.com/live/streamkey';
$outputFile = 'output.mp4';
$command = "$ffmpegPath -i $rtmpUrl -c copy $outputFile";
exec($command);
使用PHP扩展实现RTMP
虽然PHP没有内置RTMP支持,但可以通过PECL扩展如php-rtmp实现基本功能。安装后可通过以下方式使用:
$rtmp = new RTMP();
$rtmp->connect('rtmp://example.com/live');
$rtmp->publish('streamkey');
$rtmp->send($data);
$rtmp->close();
通过WebSocket中转实现
对于需要浏览器交互的场景,可以通过WebSocket中转RTMP流:
- 前端使用WebSocket连接PHP服务器
- PHP服务器与RTMP服务器建立连接
- 数据通过PHP服务器中转
示例代码片段:
$server = new WebSocketServer();
$server->onMessage = function($client, $message) use ($rtmpConnection) {
$rtmpConnection->send($message);
};
注意事项
- FFmpeg需要预先安装在服务器上
- RTMP协议通常使用1935端口,确保防火墙允许
- 直播场景需要考虑延迟和带宽问题
- 安全方面需要验证流密钥和来源
性能优化建议
- 使用多进程处理多个流
- 考虑使用Redis等缓存中间件
- 对关键操作添加日志记录
- 实现断线重连机制







