Ngnix 搭建视频直播服务器

受疫情推迟开学影响,这段时间全国如火如荼推广网络教学,前段时间搭建了edx慕课平台,但还缺点什么,就是网络直播教学,花一天时间,搭建成功,记录备用。

1. 基本技术路线

Ngnix 搭建视频直播服务器

其中,服务器采用 nginx + nginx-rtmp-module,推流采用 OBS-Studio,拉流 采用html5网页播放

2. 直播服务器安装

环境 centos7,没有安装桌面图形界面,server版

yum install -y gcc
yum install -y openssl openssl-devel
yum insall -y pcre pcre-devel
yum install -y zlib zlib-devel

git clone https://github.com/arut/nginx-rtmp-module.git

wget http://nginx.org/download/nginx-1.9.9.tar.gz

 tar -zxvf nginx-1.9.9.tar.gz
cd nginx-1.9.9

./configure --prefix=/usr/local/nginx --add-module=/root/nginx-rtmp-module --with-http_ssl_module
 make && make install

正常编译安装后可以看到 /usr/local/nginx  目录

配置文件

nano /usr/local/nginx/conf/nginx.conf

加入如下配置

rtmp {
    server {
    listen 1935;  #监听的端口
        chunk_size 4000;   #流整合的最大的块大小,这个值设置的越大 CPU 负载就越小
        #增加对hls的支持
        application hls {  #rtmp推流请求路径
            live on;   #开启实时
            hls on;   #开启hls
            hls_path /usr/local/nginx/html/hls; #推流文件保存的路径,要有写入权限
            hls_fragment 5s;   # 每个文件包含5秒的视频内容
        }

        application hls1 {    # 第二直播频道 ...
            live on; 
            hls on;  
            hls_path /usr/local/nginx/html/hls1; 
            hls_fragment 10s;  
        }
    }
}

保存后启动服务器

./sbin/nginx -c ./conf/nginx.conf

如修改配置后  nginx -s reload 命令重新读取配置

3. 推流直播  

OBS-Studio-23.2.1-Full-x64  网上下载的绿色版本,无需安装,解压即可使用

Ngnix 搭建视频直播服务器

配置推流服务器,串流**就是服务器上保存串流缓存的文件名

如果推流正常,在/usr/local/nginx/html/hls 目录下可以看到生成的文件

[[email protected] sbin]# ls /usr/local/nginx/html/hls
stream-0.ts  stream-1.ts  stream.m3u8
4. 拉流,也就是播放直播啦

采用html5 网页


<!DOCTYPE html>
<html>
    <head>
    <title>播放器</title>
        <!-- 导入的videojs是7.0版本以上的,集成VHS协议库,可播放HLS流媒体视频 -->
        <link href="css/video-js.min.css" rel="stylesheet" type="text/css">
        <script src="js/video.min.js"></script>
        <!-- 引入的videojs-flash.js插件主要是为播放rtmp视频流-->
        <script src="js/videojs-flash.min.js"></script>
    </head>
    <body>
    <video id='myvideo' width=960 height=540 class="video-js vjs-default-skin" con$
            <!-- RTMP直播源地址-->
            <source src="http://192.168.49.129/hls/stream.m3u8">
        </video>
        <script>
            var player = videojs('myvideo', {}, function(){console.log('videojs播放器 $
            player.play();
        </script>
    </body>
</html>

Ngnix 搭建视频直播服务器

正常使用直播

5. 直播现成的视频文件

可以在服务器安装 ffmpeg 作为播放源

安装:

yum install -y epel-release rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
yum repolist
rpm --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-1.el7.nux.noarch.rpm
yum repolist
yum install -y ffmpeg

使用:

ffmpeg -re -i testvideo.mp4 -c copy -f flv rtmp://192.168.49.129:1395/live/stream

下图左边是播放效果,右边是ffmpeg在推流

Ngnix 搭建视频直播服务器

 

下图播放视频文件,两路推流,两路拉流,画面流畅,没有压力

Ngnix 搭建视频直播服务器

参考多篇文章,不在此列出,谢谢!