使用nginx与nginx-http-flv-module搭建简易Web直播

# 服务器所需环境

# 下载nginx-http-flv-module

nginx-http-flv-module的开源地址:https://github.com/winshining/nginx-http-flv-module (opens new window)

git clone https://github.com/winshining/nginx-http-flv-module.git
1

# 安装nginx

nginx的官方网站:https://nginx.org/en/download.html (opens new window)

安装时候可能会报错没有安装openssl,需要执行命令:

      sudo apt-get install libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev
    
    1
      sudo yum -y install tar make openssl openssl-devel gcc pcre-devel pcre zlib zlib-devel gcc gcc-c++
    
    1
    // Make sure to add code blocks to your code group
    wget http://nginx.org/download/nginx-1.17.5.tar.gz
    tar -zxvf nginx-1.17.5.tar.gz
    cd nginx-1.8.1
    ./configure --prefix=/usr/local/nginx  --add-module=../nginx-http-flv-module --with-http_ssl_module --with-cc-opt="-Wimplicit-fallthrough=0"
    make && make install
    
    1
    2
    3
    4
    5

    创建软链接

    ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx
    
    1

    创建系统服务

    vim /etc/init.d/nginx
    
    1
    详细配置文件
      #! /bin/sh
      # chkconfig: 2345 55 2
      # Description: Startup script for nginx webserver on Debian. Place in /etc/init.d and
      # run 'update-rc.d -f nginx defaults', or use the appropriate command on your
      # distro. For CentOS/Redhat run: 'chkconfig --add nginx'
      
      ### BEGIN INIT INFO
      # Provides:          nginx
      # Required-Start:    $all
      # Required-Stop:     $all
      # Default-Start:     2 3 4 5
      # Default-Stop:      0 1 6
      # Short-Description: starts the nginx web server
      # Description:       starts nginx using start-stop-daemon
      ### END INIT INFO
      
      # Author:   licess
      # website:  http://lnmp.org
      
      PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
      NAME=nginx
      NGINX_BIN=/usr/local/nginx/sbin/$NAME
      CONFIGFILE=/usr/local/nginx/conf/$NAME.conf
      PIDFILE=/tmp/logs/nginx/$NAME.pid
      
      case "$1" in
          start)
              echo -n "Starting $NAME... "
      
              if netstat -tnpl | grep -q nginx;then
                  echo "$NAME (pid `pidof $NAME`) already running."
                  exit 1
              fi
      
              $NGINX_BIN -c $CONFIGFILE
      
              if [ "$?" != 0 ] ; then
                  echo " failed"
                  exit 1
              else
                  echo " done"
              fi
              ;;
      
          stop)
              echo -n "Stoping $NAME... "
      
              if ! netstat -tnpl | grep -q nginx; then
                  echo "$NAME is not running."
                  exit 1
              fi
      
              $NGINX_BIN -s stop
      
              if [ "$?" != 0 ] ; then
                  echo " failed. Use force-quit"
                  exit 1
              else
                  echo " done"
              fi
              ;;
      
          status)
              if netstat -tnpl | grep -q nginx; then
                  PID=`pidof nginx`
                  echo "$NAME (pid $PID) is running..."
              else
                  echo "$NAME is stopped"
                  exit 0
              fi
              ;;
      
          force-quit)
              echo -n "Terminating $NAME... "
      
              if ! netstat -tnpl | grep -q nginx; then
                  echo "$NAME is not running."
                  exit 1
              fi
      
              kill `pidof $NAME`
      
              if [ "$?" != 0 ] ; then
                  echo " failed"
                  exit 1
              else
                  echo " done"
              fi
              ;;
      
          restart)
              $0 stop
              sleep 1
              $0 start
              ;;
      
          reload)
              echo -n "Reload service $NAME... "
      
              if netstat -tnpl | grep -q nginx; then
                  $NGINX_BIN -s reload
                  echo " done"
              else
                  echo "$NAME is not running, can't reload."
                  exit 1
              fi
              ;;
      
          configtest)
              echo -n "Test $NAME configure files... "
      
              $NGINX_BIN -t
              ;;
      
          *)
              echo "Usage: $0 {start|stop|force-quit|restart|reload|status|configtest}"
              exit 1
              ;;
      
      esac
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      #!/bin/sh
      #
      # nginx - this script starts and stops the nginx daemon
      #
      # chkconfig:   - 85 15
      # description:  NGINX is an HTTP(S) server, HTTP(S) reverse \
      #               proxy and IMAP/POP3 proxy server
      # processname: nginx
      # config:      /usr/local/nginx/conf/nginx.conf
      # config:      /etc/sysconfig/nginx
      # pidfile:     /usr/local/nginx/logs/nginx.pid
      # Source function library.
      . /etc/rc.d/init.d/functions
      # Source networking configuration.
      . /etc/sysconfig/network
      # Check that networking is up.
      [ "$NETWORKING" = "no" ] && exit 0
      nginx="/usr/local/nginx/sbin/nginx"
      prog=$(basename $nginx)
      NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
      [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
      lockfile=/var/lock/subsys/nginx
      make_dirs() {
         # make required directories
         user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
         if [ -z "`grep $user /etc/passwd`" ]; then
             useradd -M -s /bin/nologin $user
         fi
         options=`$nginx -V 2>&1 | grep 'configure arguments:'`
         for opt in $options; do
             if [ `echo $opt | grep '.*-temp-path'` ]; then
                 value=`echo $opt | cut -d "=" -f 2`
                 if [ ! -d "$value" ]; then
                     # echo "creating" $value
                     mkdir -p $value && chown -R $user $value
                 fi
             fi
         done
      }
      start() {
          [ -x $nginx ] || exit 5
          [ -f $NGINX_CONF_FILE ] || exit 6
          make_dirs
          echo -n $"Starting $prog: "
          daemon $nginx -c $NGINX_CONF_FILE
          retval=$?
          echo
          [ $retval -eq 0 ] && touch $lockfile
          return $retval
      }
      stop() {
          echo -n $"Stopping $prog: "
          killproc $prog -QUIT
          retval=$?
          echo
          [ $retval -eq 0 ] && rm -f $lockfile
          return $retval
      }
      restart() {
          configtest || return $?
          stop
          sleep 1
          start
      }
      reload() {
          configtest || return $?
          echo -n $"Reloading $prog: "
          killproc $nginx -HUP
          RETVAL=$?
          echo
      }
      force_reload() {
          restart
      }
      configtest() {
        $nginx -t -c $NGINX_CONF_FILE
      }
      rh_status() {
          status $prog
      }
      rh_status_q() {
          rh_status >/dev/null 2>&1
      }
      case "$1" in
          start)
              rh_status_q && exit 0
              $1
              ;;
          stop)
              rh_status_q || exit 0
              $1
              ;;
          restart|configtest)
              $1
              ;;
          reload)
              rh_status_q || exit 7
              $1
              ;;
          force-reload)
              force_reload
              ;;
          status)
              rh_status
              ;;
          condrestart|try-restart)
              rh_status_q || exit 0
                  ;;
          *)
              echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
              exit 2
      esac
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      // Make sure to add code blocks to your code group

      赋予脚本可执行权限

      chmod a+x /etc/init.d/nginx
      
      1

      将nginx服务加入chkconfig管理列表

      chkconfig --add /etc/init.d/nginx
      chkconfig nginx on
      # 启动
      systemctl start nginx
      
      1
      2
      3
      4

      # 修改nginx配置文件

      mkdir -p /usr/share/nginx/html/hls
      
      1
      vi /usr/local/nginx/conf/nginx.conf
      
      1

      加入以下内容rtmp模块:(rtmp{}的内容和http{}为同级,位置不要放错直接放到文件最后就行了)

      rtmp {
          server {
              listen 1935;  #监听的端口可以自己改
              chunk_size 4000;
              application hls {  #rtmp推流请求路径
                  live on;
                  hls on;
                  hls_path /usr/share/nginx/html/hls;
                  hls_fragment 5s;
              }
          }
      }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12

      修改http中的server模块:

      server {
          listen       80;  #端口可自定义
          server_name  localhost;
          #charset koi8-r;
          #access_log  logs/host.access.log  main;
          location / {
              add_header Cache-Control no-cache;
              add_header 'Access-Control-Allow-Origin' '*' always;
              add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
              add_header 'Access-Control-Allow-Headers' 'Range';
              root   /usr/share/nginx/html;  #网站路径
              index  index.html index.htm;
          }
          #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;
          }
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19

      然后启动 nginx

      # 启动
      systemctl start nginx
      # 查看状态
      systemctl status nginx
      # 停止
      systemctl stop nginx
      
      # 重载配置
      nginx -s reload
      # 测试配置是否正确
      nginx -t
      
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11

      # 配置防火墙

      firewall-cmd --zone=public --add-port=80/tcp --permanent
      firewall-cmd --zone=public --add-port=1935/tcp --permanent
      ##重新载入
      firewall-cmd --reload
      
      1
      2
      3
      4

      # 开始推流

      打开 OBS (opens new window),进入主界面

      文件->设置->串流 中填写信息:URL为 rtmp://xxx:1935/hls,xxx为你的服务器的IP地址

      秘钥可以随便填写一个,例如填写80ab164c-d9be-4867-8043-1e266e019dbb,随机生成ID网站 (opens new window)

      填写完毕后,回主界面,点击开始推流,就说明我们的流媒体服务器搭建成功了

      打开/usr/share/nginx/html/hls,里面出现80ab164c-d9be-4867-8043-1e266e019dbb.m3u8说明推流正常了

      # 观看直播(拉流)

      西瓜视频播放器 (opens new window)DPlayer播放器 (opens new window)阿里云player播放器 (opens new window)

      vi /usr/share/nginx/html/index.html
      
      1
      详细示例代码
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge" >
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
        <title>Tiger-live</title>
        <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css" />
        <link rel="icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
        <script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-min.js"></script>
        <style>
            .citrons{
                position: absolute;
                width: 100%;
                height: 100%;
            }
            *{
                margin: 0;
                padding: 0;
                overflow:hidden;
            }
        </style>
        </head>
        <body>
        <div class="citrons">
        <div class="prism-player" id="player-con"></div>
        </div>
        <script>
        var player = new Aliplayer({
          "id": "player-con",
          "source": "http://IP地址或者域名/hls/80ab164c-d9be-4867-8043-1e266e019dbb.m3u8",
          "width": "100%",
          "height": "100%",
          "autoplay": true,
          "isLive": true,
          "rePlay": false,
          "playsinline": true,
        /*  "cover":"http://IP地址或者域名/ow.jpg", */
          "preload": true,
          "controlBarVisibility": "hover",
          "useH5Prism": true,
          "skinLayout":[
           {name: "bigPlayButton", align: "blabs", x: 30, y: 80},
            {
              name: "H5Loading", align: "cc"
            },
            {name: "errorDisplay", align: "tlabs", x: 0, y: 0},
            {name: "infoDisplay"},
            {name:"tooltip", align:"blabs",x: 0, y: 56},
            {name: "thumbnail"},
            {
              name: "controlBar", align: "blabs", x: 0, y: 0,
              children: [
                {name: "progress", align: "blabs", x: 0, y: 44},
                {name: "playButton", align: "tl", x: 15, y: 12},
                {name: "fullScreenButton", align: "tr", x: 10, y: 12},
                /*{name:"setting", align:"tr",x:15, y:12},*/
                {name: "volume", align: "tr", x: 5, y: 10}
              ]
            }
          ]
        }, function (player) {
            player._switchLevel = 0;
            player.on('liveStreamStop',function(e) {
                alert('还没开播呢');
            });
          }
        );
        </script>
        </body>
        </html>
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        40
        41
        42
        43
        44
        45
        46
        47
        48
        49
        50
        51
        52
        53
        54
        55
        56
        57
        58
        59
        60
        61
        62
        63
        64
        65
        66
        67
        68
        69
        70
        71
        72
        <!DOCTYPE html>
        <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="IE=edge" >
        <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
        <title>Tiger-live</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dplayer@1.25.0/dist/DPlayer.min.css">
        <script src="https://cdn.jsdelivr.net/npm/dplayer@1.25.0/dist/DPlayer.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
        <style>
            #dplayer{
                width: 100%;
                height: 100%;
        		position: fixed;
            }
        	*{
                margin: 0;
                padding: 0;
            }
        </style>
        </head>
        <body>
        <div id="dplayer"></div>
        <script>
        const dp = new DPlayer({
            container: document.getElementById('dplayer'),
            live: true,
        	autoplay: true,
            danmaku: false,
            video: {
                url: 'http://IP地址或者域名/hls/80ab164c-d9be-4867-8043-1e266e019dbb.m3u8',
                type: 'hls',
            },
        });
        </script>
        </body>
        </html>
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        // Make sure to add code blocks to your code group