2.5 你的第一个直播
上一节我们搭建了nginx-rtmp-module环境,本节我们来搭建一个简单的直播
1.进入配置文件目录
打开配置文件目录,nginx.conf为默认加载的配置文件,nginx.conf.default为默认配置文件备份,如图2-7所示。
cd /usr/local/nginx/conf/

图2-7
2.修改默认配置文件
修改系统服务脚本init.d。
cd /etc/init.d/
vim nginx
修改文件中nginx.conf为live.conf,修改默认service nginx服务指向的配置文件如图2-8。
NGINX_CONF_FILE="/usr/local/nginx/conf/live.conf"

图2-8
rename nginx live nginx.conf 
#修改nginx为live目标文件nginx.conf
3.精简及确认live.conf
精简后的live.conf,去除了默认注释。
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
   }
}
#修改文件名后,我们将系统产生的配置文件进行精简并检查结果
service nginx configtest
#nginx: the configuration file /usr/local/nginx/conf/live.conf syntax is ok
#nginx: configuration file /usr/local/nginx/conf/live.conf test is successful
4. 配置RTMP直播
rtmp标签
- nginx-rtmp-module的基础标签所有服务都配在其中。
server标签
- 服务标签,一个rtmp服务中可以有多个server标签,每个server可以监听不同端口,server中的配置是应用于所有application标签的。
application标签
- 应用标签,一个server标签中可以有多个application标签,application标签中的配置是应用于其本身的,application name确保了在请求时准确的application划分。
worker_processes  1;
events {
    worker_connections  1024;
}
rtmp{
   server{
       listen 1935;
       application mylive{
           live on;
       }
   }
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
   }
}
5. 防火墙规则
vim /etc/sysconfig/iptables
#iptables中可以设置防火墙规则 
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 21 -j ACCEPT
-A INPUT -p tcp --dport 1935 -j ACCEPT 
#开启tcp的1935端口写入权限,-p代表了指定协议
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
rtmp是基于tcp的实现
service iptables restart
重启防火墙生效配置
6. 推流
ffmpeg于推拉流在之后的文章中说明,如图2-9所示推流中的ffmpeg
ffmpeg -i f:\xx.flv -r 25 -b 4M -f flv rtmp://172.26.22.30:1935/mylive/6

图2-9
7.拉流
我们使用VLC流媒体播放器来拉流,可以看到我直播的动画片,可以观看了,如图2-10所示。

图2-10