直播实现 php
直播功能实现(PHP方案)
核心组件需求
- 流媒体服务器(如Nginx-RTMP、SRS)
- 视频采集端(OBS/手机推流)
- 播放器(HLS/FLV协议)
- PHP后端处理业务逻辑
推流端配置
安装OBS Studio并配置推流地址:
rtmp://your-server-ip/live/stream-key
手机端可使用Larix Broadcaster等APP,需相同RTMP地址格式。
服务器搭建(Nginx-RTMP)
修改nginx.conf添加RTMP模块配置:
rtmp {
server {
listen 1935;
application live {
live on;
hls on;
hls_path /tmp/hls;
hls_fragment 3s;
}
}
}
需同时配置HTTP服务器用于HLS分发:
location /hls {
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
alias /tmp/hls;
}
PHP处理逻辑
创建频道管理接口(channel.php):
<?php
$stream_key = uniqid('channel_');
$rtmp_url = "rtmp://your-server-ip/live/{$stream_key}";
$hls_url = "http://your-server-ip/hls/{$stream_key}.m3u8";
echo json_encode([
'rtmp' => $rtmp_url,
'hls' => $hls_url,
'status' => 'active'
]);
前端播放器实现
使用flv.js或hls.js库:
<video id="player" controls></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
const video = document.getElementById('player');
if(Hls.isSupported()) {
const hls = new Hls();
hls.loadSource("<?php echo $hls_url; ?>");
hls.attachMedia(video);
}
</script>
录制功能扩展
在RTMP配置中添加录制指令:
recorder rec1 {
record all;
record_path /var/rec;
record_unique on;
}
安全增强措施
-
推流鉴权(PHP生成临时token):
$auth_token = hash_hmac('sha256', $stream_key, 'secret'); -
Nginx验证模块:
on_publish http://your-server-ip/auth.php;
auth.php示例:
<?php
$valid = $_GET['token'] === hash_hmac('sha256', $_GET['name'], 'secret');
header('HTTP/1.1 401 Unauthorized');
if($valid) exit(header('HTTP/1.1 200 OK'));
性能优化建议
- 开启Nginx缓存静态切片
- 使用CDN分发HLS流
- 限制单IP连接数
- 监控服务器负载
移动端适配要点
-
低延迟配置:
hls_fragment 1s; hls_playlist_length 3s; -
自适应码率方案:
hls_variant _low BANDWIDTH=640000; hls_variant _mid BANDWIDTH=1500000;
完整实现需配合具体业务需求调整参数,建议使用专业直播SaaS服务作为生产环境解决方案。







