首先了解一下相关协议,可以阅读此文章。本文方案使用的是最早出现、延迟最低基于TCP的RTMP协议,服务器端只需要Nginx,外加一个RTMP模块。
安装不赘述。如果已有yum等安装的Nginx,通过 nginx -V 得到编译参数, 下载相同版本的Nginx源码,在编译参数最后添加 –add-module=[下载解压的RTMP模块目录]重新编译安装即可。
配置 Nginx,在主配置文件 nginx.conf 的 http 模块下新增 rtmp 模块:
rtmp { server { allow publish all; listen 1935; ping 30s; notify_method get; application myapp { live on; # sample play/publish handlers #on_play http://localhost:8080/on_play; #on_publish http://localhost:8080/on_publish; # sample recorder #recorder rec1 { # record all; # record_interval 30s; # record_path /tmp; # record_unique on; #} # sample HLS hls on; hls_path /tmp/hls; # hls_sync 100ms; hls_fragment 5s; hls_cleanup off; record all; record_path /tmp/record; record_unique on; } # Video on demand application vod { # play /var/Videos; play /usr/local/video; } # Video on demand over HTTP #application vod_http { # play http://localhost:8080/vod/; #} } }
上边定义了一个名为 myapp 的应用, 开启了直播 live, 同时也开启了 hls 和视频录制 record .此时若进行直播,hls功能会将直播流录制成 ts 视频片段, record 功能则将直播流完整录制成flv视频文件,视频使用 h.264 编码,音频是 aac 编码. hls 主要是为H5移动端服务,还需要配置一个 http 服务器:
server { listen 8090; server_name 134.175.xxx.xxx; #charset koi8-r; #access_log logs/host.access.log main; # location / { # root /tmp/hls; # index index.html index.htm; #} #HLS配置开始,这个配置为了`客户端`能够以http协议获取HLS的拉流 location / { # Serve HLS fragments types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; } root /tmp/hls; add_header Cache-Control no-cache; } #HLS配置结束 # rtmp stat location /stat { rtmp_stat all; rtmp_stat_stylesheet stat.xsl; } location /stat.xsl { # you can move stat.xsl to a different location # root /usr/build/nginx-rtmp-module; root /usr/local/src/nginx-rtmp-module-1.2.1; } # rtmp control location /control { rtmp_control all; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
万事具备,可以在服务器端使用 ffmpeg 进行流测试:
ffmpeg -re -i /usr/local/video/WeChat_20200206235642.mp4 -c copy -f flv rtmp://134.175.xxx.xxx/myapp/wechat
这里推向的主机不是localhost, 这也是上边 rtmp 中添加 allow publish all 的原因, 不添加这一句是只能向 localhost 推的. 我们在本地打开支持 rtmp和hls协议的客户端如 potplayer, 打开链接即可观看:
rtmp地址是: rtmp://134.175.xxx.xxx/myapp/wechat http地址是: http://134.175.xxx.xxx/wechat.m3u8
http 地址,在移动端使用自带浏览器打开也能播放, Android 和 IOS 均支持, 只是实际测试效果并不理想.
也可以在本地进行真实推流测试, 安装 OBS Studio 软件,在设置的推流一项,服务选择自定义, 服务器是写到 rtmp 中创建的应用名部分, 串流密钥则是我们随便自定义的,类似上边使用 ffmpeg 推流中最后的 wechat .
假如我们填写串流密码为 live,这样我们实际推流后, 生成的 m3u8 文件是 live.m3u8, 生成的 ts 视频片段就是 live-0.ts, live-1.ts等,录制的视频文件是 live-1583229603.flv,命名会默认添加时间戳后缀.
以上就是最简单的直播系统, 当然实际生产环境中要比这个复杂得多,前端录制,上传,后端转码,推流,各方面还有很多的优化,否则根本无法流畅观看.除了最基本的画面,还有聊天系统,奖赏,特效,连麦等等,一般商用还是得接入第三方大厂如阿里,腾讯,七牛等成熟的解决方案!