最近研究了关于nginx搭建流媒体服务的相关资料,总结一下根据nginx中的rtmp模块来搭建流媒体服务。
将rtmp模块下载后放在nginx中。
然后编辑conf文件夹下的nginx.conf文件:
worker_processes 1;
error_log logs/error.log debug;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
chunk_size 4096;
application live {
live on;
on_publish http://127.0.0.1:18081/live-stream/stream/auth;
hls on;
on_record_done http://127.0.0.1:18081/live-stream/stream/down;
hls_path nginx-rtmp-module/tmp/app/;
hls_fragment 5s;
recorder rec { #启用录制
record all; #手动控制录制启停
record_suffix %Y%m%d%H%M%S.flv;
record_path nginx-rtmp-module/tmp/vod; #录制保存地址
# record_unique on;
}
}
application vod{ #rtmp点播
play nginx-rtmp-module/tmp/vod/;
}
}
}
http {
server {
listen 8080;
server_tokens off;
location = /stat {
rtmp_stat all;
rtmp_stat_stylesheet stat.xsl;
}
location /control { #控制器
rtmp_control all;
}
location /live/ { #hls直播地址
#server hls fragments
types{
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
alias nginx-rtmp-module/tmp/app/;
expires -1;
}
location /vod/ { #hls点播地址
vod hls;
root /home/nieyabing/nginx/nginx-rtmp-module/tmp;
}
location /dl/ {
root /home/nieyabing/nginx/nginx-rtmp-module/tmp;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
}
}
}
on_publish 字段是在直播开始前访问该程序接口,我们可以在该接口中定义一些方法来对直播进行处理,比如鉴权等功能。
接口的方法大致如下:
@ApiOperation("开始推流")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "登录名", required = true, dataType = "String", paramType="query"),
@ApiImplicitParam(name = "live", value = "密钥", required = true, dataType = "String", paramType="query"),
@ApiImplicitParam(name = "type", value = "程序名", required = true, dataType = "String", paramType="query"),
@ApiImplicitParam(name = "tcurl", value = "推流地址", required = true, dataType = "String", paramType="query")
})
@PostMapping("/auth")
public @ResponseBody CommonReturnType auth(HttpServletRequest request, HttpServletResponse response, String name, String live,String type, String tcurl) {
System.out.println("开始验证直播推流");
CommonReturnType dataVo = new CommonReturnType();
//处理自己的业务代码
//处理完业务成功后返回success成功
if(true){
dataVo = CommonReturnType.create("success");
}else{
response.setHeader("error","sys error");
response.setStatus(500);
}
return dataVo;
}
on_record_done是当直播结束后访问的接口,接口传输的参数与on_publish的参数一样。