服务器所需环境

下载nginx-http-flv-module

nginx-http-flv-module的github地址:https://github.com/winshining/nginx-http-flv-module

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

安装nginx

nginx的官方网站:https://nginx.org/en/download.html
安装时候可能会报错没有安装openssl,需要执行命令:

##Ubuntu:
sudo apt-get install libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev
##Centos:
sudo yum -y install tar make openssl openssl-devel gcc pcre-devel pcre zlib zlib-devel gcc gcc-c++
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

创建软链接

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

创建系统服务

vim /etc/init.d/nginx

centos系统:

#!/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

ubuntu系统:

#! /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

赋予脚本可执行权限

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

将nginx服务加入chkconfig管理列表

chkconfig --add /etc/init.d/nginx
chkconfig nginx on
# 启动
systemctl start nginx

修改nginx配置文件

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

加入以下内容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;
        }
    }
}

修改http中的server模块(重点就是修改端口和location ):

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;
    }

然后启动nginx:

# 启动
systemctl start nginx
# 查看状态
systemctl status nginx
# 停止
systemctl stop nginx

# 重载配置
nginx -s reload
# 测试配置是否正确
nginx -t

配置防火墙

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

开始推流

打开OBS,进入主界面
在文件->设置->串流 中填写信息:URL为 rtmp://xxx:1935/hls,xxx为你的服务器的IP地址(如我之前所说可以绑定域名),hls是用来存放流媒体的
秘钥可以随便填写一个,用来播放的时候识别播放哪个流媒体的,例如填写80ab164c-d9be-4867-8043-1e266e019dbb,随机生成ID网站
填写完毕后,回主界面,点击开始推流,就说明我们的流媒体服务器搭建成功了
打开/usr/share/nginx/html/hls,里面出现80ab164c-d9be-4867-8043-1e266e019dbb.m3u8说明推流正常了

观看直播(拉流)

这里推荐一个播放器,可以自动生成页面的————阿里云player播放器或者DPlayer

vi /usr/share/nginx/html/index.html

阿里云player播放器

<!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>

Dplayer 播放器

<!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>
文章目录