CentOS obs直播RTMP協定推流到Nginx串流媒體伺服器到VUE使用HLS直播

2022-09-26 18:01:23

1. 釋出打包前端管理平臺(ant-design-vue)

2. 釋出打包後端(.NET6-WebApi)

.NET6 webAPI

orm: free sql

資料庫:mysql5.7

3. 釋出打包H5端(uni)

播放器使用:

import Player from 'xgplayer'; // npm install xgplayer
import HlsJsPlayer from "xgplayer-hls.js"; // 直播流m3u8(hls) npm install xgplayer-hls.js

4. 伺服器安裝.NET6環境:https://learn.microsoft.com/zh-cn/dotnet/core/install/linux-centos

安裝 .NET 之前,請執行以下命令,將 Microsoft 包簽名金鑰新增到受信任金鑰列表,並新增 Microsoft 包儲存庫。 開啟終端並執行以下命令:
sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
安裝 SDK
.NET SDK 使你可以通過 .NET 開發應用。 如果安裝 .NET SDK,則無需安裝相應的執行時。 若要安裝 .NET SDK,請執行以下命令:
sudo yum install dotnet-sdk-6.0
安裝執行時
通過 ASP.NET Core 執行時,可以執行使用 .NET 開發且未提供執行時的應用。 以下命令將安裝 ASP.NET Core 執行時,這是與 .NET 最相容的執行時。 在終端中,執行以下命令:
 
sudo yum install aspnetcore-runtime-6.0

 

5. 伺服器安裝寶塔:https://www.bt.cn/new/download.html

yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh ed8484bec

6. 伺服器安裝supervisor程序守護

supervisord是服務相關的命令
supervisorctl是使用者端相關的命令

安裝命令:

yum install -y supervisor

檢視狀態:

supervisord -v 

解除安裝:

yum -y remove supervisor

在/etc建立檔案目錄supervisor

在/etc/supervisor下建立檔案目錄supervisord.d

在/etc/supervisor下上傳檔案supervisord.conf,內容如下:

; Sample supervisor config file.

[unix_http_server]
file=/run/supervisor/supervisor.sock   ; (the path to the socket file)
;chmod=0700                 ; sockef file mode (default 0700)
;chown=nobody:nogroup       ; socket file uid:gid owner
;username=user              ; (default is no username (open server))
;password=123               ; (default is no password (open server))

[inet_http_server]         ; inet (TCP) server disabled by default
port=*:9001        ; (ip_address:port specifier, *:port for all iface)
;username=user              ; (default is no username (open server))
;password=123               ; (default is no password (open server))

[supervisord]
logfile=/www/log/supervisor/supervisord.log  ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB       ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10          ; (num of main logfile rotation backups;default 10)
loglevel=info               ; (log level;default info; others: debug,warn,trace)
pidfile=/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false              ; (start in foreground if true;default false)
minfds=1024                 ; (min. avail startup file descriptors;default 1024)
minprocs=200                ; (min. avail process descriptors;default 200)
;umask=022                  ; (process file creation umask;default 022)
;user=chrism                 ; (default is current user, required if root)
;identifier=supervisor       ; (supervisord identifier, default is 'supervisor')
;directory=/tmp              ; (default is not to cd during start)
;nocleanup=true              ; (don't clean up tempfiles at start;default false)
;childlogdir=/tmp            ; ('AUTO' child log dir, default $TEMP)
;environment=KEY=value       ; (key value pairs to add to environment)
;strip_ansi=false            ; (strip ansi escape codes in logs; def. false)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///run/supervisor/supervisor.sock ; use a unix:// URL  for a unix socket
serverurl=http://*:9001 ; use an http:// url to specify an inet socket
;username=chris              ; should be same as http_username if set
;password=123                ; should be same as http_password if set
;prompt=mysupervisor         ; cmd line prompt (default "supervisor")
;history_file=~/.sc_history  ; use readline history if available

; The below sample program section shows all possible program subsection values,
; create one or more 'real' program: sections to be able to control them under
; supervisor.

;[program:theprogramname]
;command=/bin/cat              ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1                    ; number of processes copies to start (def 1)
;directory=/tmp                ; directory to cwd to before exec (def no cwd)
;umask=022                     ; umask for process (default None)
;priority=999                  ; the relative start priority (default 999)
;autostart=true                ; start at supervisord start (default: true)
;autorestart=true              ; retstart at unexpected quit (default: true)
;startsecs=10                  ; number of secs prog must stay running (def. 1)
;startretries=3                ; max # of serial start failures (default 3)
;exitcodes=0,2                 ; 'expected' exit codes for process (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism                   ; setuid to this UNIX account to run the program
;redirect_stderr=true          ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (default 10)
;stdout_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10     ; # of stderr logfile backups (default 10)
;stderr_capture_maxbytes=1MB   ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A=1,B=2           ; process environment additions (def no adds)
;serverurl=AUTO                ; override serverurl computation (childutils)

; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.

;[eventlistener:theeventlistenername]
;command=/bin/eventlistener    ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1                    ; number of processes copies to start (def 1)
;events=EVENT                  ; event notif. types to subscribe to (req'd)
;buffer_size=10                ; event buffer queue size (default 10)
;directory=/tmp                ; directory to cwd to before exec (def no cwd)
;umask=022                     ; umask for process (default None)
;priority=-1                   ; the relative start priority (default -1)
;autostart=true                ; start at supervisord start (default: true)
;autorestart=unexpected        ; restart at unexpected quit (default: unexpected)
;startsecs=10                  ; number of secs prog must stay running (def. 1)
;startretries=3                ; max # of serial start failures (default 3)
;exitcodes=0,2                 ; 'expected' exit codes for process (default 0,2)
;stopsignal=QUIT               ; signal used to kill process (default TERM)
;stopwaitsecs=10               ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism                   ; setuid to this UNIX account to run the program
;redirect_stderr=true          ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path        ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10     ; # of stdout logfile backups (default 10)
;stdout_events_enabled=false   ; emit events on stdout writes (default false)
;stderr_logfile=/a/path        ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB   ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups        ; # of stderr logfile backups (default 10)
;stderr_events_enabled=false   ; emit events on stderr writes (default false)
;environment=A=1,B=2           ; process environment additions
;serverurl=AUTO                ; override serverurl computation (childutils)

; The below sample group section shows all possible group values,
; create one or more 'real' group: sections to create "heterogeneous"
; process groups.

;[group:thegroupname]
;programs=progname1,progname2  ; each refers to 'x' in [program:x] definitions
;priority=999                  ; the relative start priority (default 999)

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

[include]
files = supervisord.d/*.conf ;這行預設是載入/etc/supervisord.d/目錄內所有conf字尾的設定,喜歡用ini的可以改成ini
supervisord.conf

在/etc/supervisor/supervisord.d下上傳檔案xx.conf,內容如下:

[program:appname]
command=dotnet appname.dll --urls=http://*:5000   ;要執行的命令
directory=/www/api ;命令執行的目錄
environment=ASPNETCORE__ENVIRONMENT=Production ;環境變數
user=root  ;程序執行的使用者身份
stopsignal=INT
autostart=true ;是否自動啟動
autorestart=true ;是否自動重啟
startsecs=3 ;自動重啟間隔
stderr_logfile=/www/log/appname.err.log ;標準錯誤紀錄檔
stdout_logfile=/www/log/appname.out.log ;標準輸出紀錄檔
[supervisord]
[supervisorctl]

執行啟動命令:

supervisord -c /etc/supervisor/supervisord.conf

啟動成功後:執行下面命令檢視,會出現一個

ps aux|grep supervisord
root     11589  0.0  0.0 112828   988 pts/0    S+   16:57   0:00 grep --color=auto supervisord
root     30510  0.0  0.4 245472 17220 ?        Ss   16:12   0:00 /usr/bin/python /usr/bin/supervisord -c /etc/supervisor/supervisord.conf

啟動程式:

supervisorctl start  appname
supervisorctl stop  appname

檢視狀態:

supervisorctl status
appname    RUNNING   pid 20538, uptime 0:24:24

檢視狀態:瀏覽器輸入:http://*:9001/

 

 檢視埠以及appanme執行程序

lsof -i:5000
ps -f |grep appname
 設定Supervisor開機啟動
systemctl enable supervisord.service
 檢查是否開機啟動
systemctl is-enabled supervisord

如果啟動錯誤,檢視紀錄檔

supervisorctl tail dcapi stdout

 

 log紀錄檔地址:/www/log/supervisor/supervisord.log

遇到錯誤:Unlinking stale socket /run/supervisor/supervisor.sock

解決辦法:

執行命令:

nlink /run/supervisor/supervisor.sock

 

7. 寶塔安裝Mysql5.7

 

8. 伺服器安裝Nginx(基於RTMP模式的)

沒有git請輸入以下命令

yum -y install git

開始下載nginx-rtmp,記住cd到一個碟符進行下載,建議cd ~,也可以直接從git下載瞭然後複製上去/www/server/nginx/nginx-rtmp-module

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

修改組態檔:新增內容:--add-module=/root/nginx-rtmp-module

vim /www/server/panel/install/nginx.sh

可以下載到本地修改,然後上傳到伺服器路徑下:/www/server/panel/install/nginx.sh

修改位置:./configure --add-module=/root/nginx-rtmp-module --user=www ........................

 

 

使用sh命令安裝

sh /www/server/panel/install/nginx.sh install1.22

9. Nginx設定 ,修改寶塔》軟體管理》Nginx1.22管理》設定修改如下:

user  www www;
worker_processes auto;
error_log  /www/wwwlogs/nginx_error.log  crit;
pid        /www/server/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;

stream {
    log_format tcp_format '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time';
  
    access_log /www/wwwlogs/tcp-access.log tcp_format;
    error_log /www/wwwlogs/tcp-error.log;
    include /www/server/panel/vhost/nginx/tcp/*.conf;
}

events
    {
        use epoll;
        worker_connections 51200;
        multi_accept on;
    }
#RTMP服務,新增部分:
rtmp_auto_push on;
rtmp{
    server{
        listen 1935;        #伺服器埠
        chunk_size 4096;    #資料傳輸塊的大小
        
        application vod{
            play ./vod;   #視訊檔存放位置
        }
        application live{
            live on;                     #開啟直播
            hls on;              
            hls_path /www/m3u8File;          
            hls_fragment 5s;             #每個視訊切片的時長
            hls_playlist_length 16s;
            recorder myRecord {
                    record_path /rec;
            record all manual;
                    record_suffix -%Y-%m-%d-%H_%M_%S.flv;
            }
            hls_continuous on;          #連續模式
            hls_cleanup on;             #對多餘的切片進行刪除
            hls_nested on;              #巢狀模式
        }
    }
}
#RTMP服務,新增完畢


http
    {
        include       mime.types;
        #include luawaf.conf;

        include proxy.conf;

        default_type  application/octet-stream;

        server_names_hash_bucket_size 512;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;

        sendfile   on;
        tcp_nopush on;

        keepalive_timeout 60;

        tcp_nodelay on;

        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;
        fastcgi_intercept_errors on;

        gzip on;
        gzip_min_length  1k;
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
        gzip_disable   "MSIE [1-6]\.";

        limit_conn_zone $binary_remote_addr zone=perip:10m;
        limit_conn_zone $server_name zone=perserver:10m;

        server_tokens off;
        access_log off;

server
    {
        listen 888;
        server_name phpmyadmin;
        index index.html index.htm index.php;
        root  /www/server/phpmyadmin;

        #error_page   404   /404.html;
        include enable-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /\.
        {
            deny all;
        } 
        access_log  /www/wwwlogs/access.log;
    }
include /www/server/panel/vhost/nginx/*.conf;
}
RTMP-Nginx設定

找到某個80埠的Nginx設定,修改:

server
{
    listen 80;
    server_name xxxxxxx;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/live;

    #SSL-START SSL相關設定,請勿刪除或修改下一行帶註釋的404規則
    #error_page 404/404.html;
    #SSL-END

    #ERROR-PAGE-START  錯誤頁設定,可以註釋、刪除或修改
    #error_page 404 /404.html;
    #error_page 502 /502.html;
    #ERROR-PAGE-END

    #PHP-INFO-START  PHP參照設定,可以註釋或修改
    include enable-php-00.conf;
    #PHP-INFO-END
    try_files $uri $uri/ /index.html;
    #REWRITE-START URL重寫規則參照,修改後將導致面板設定的偽靜態規則失效
    include /www/server/panel/vhost/rewrite/www.live.com.conf;
    #REWRITE-END

    #禁止存取的檔案或目錄
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }

    #一鍵申請SSL證書驗證目錄相關設定
    location ~ \.well-known{
        allow all;
    }

    #禁止在證書驗證目錄放入敏感檔案
    if ( $uri ~ "^/\.well-known/.*\.(php|jsp|py|js|css|lua|ts|go|zip|tar\.gz|rar|7z|sql|bak)$" ) {
        return 403;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
        error_log /dev/null;
        access_log /dev/null;
    }

    location ~ .*\.(js|css)?$
    {
        expires      12h;
        error_log /dev/null;
        access_log /dev/null;
    }

#新增部分
    location /live{
            types{
                #m3u8 type設定
                application/vnd.apple.mpegurl m3u8;
                #ts分片檔案設定
                video/mp2t ts;
            }
              #存取許可權開啟,否則存取這個地址會報403
                        autoindex on;
                        
            #指向存取m3u8檔案目錄
            alias /www/m3u8File;
            expires -1;
            add_header Cache-Control no-cache;
            #防止跨域問題
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';  
        }
         location /control{
            rtmp_control all;
        }
        
        location /stat{
            rtmp_stat all;
            rtmp_stat_stylesheet stat.xsl;
        }
        location /stat.xsl{
            root ./nginx-rtmp-module;
        }
#新增完畢
    access_log  /www/wwwlogs/www.live.com.log;
    error_log  /www/wwwlogs/www.live.com.error.log;
}
拉流設定

在Nginx伺服器位置建立一個目錄:/www/server/panel/m3u8File

10. 開始直播及推流

OBS推流設定服務地址:rtmp://127.0.0.1:1935/live

串流金鑰:001

然後開始推流,在伺服器地址/www/server/panel/m3u8File下面會生成001的檔案目錄,然後001檔案目錄裡面會出現很多*.ts檔案,以及一個index.mu38檔案

拉流地址: http://127.0.0.1/live/001/index.m3u8

拉流地址:rtmp://127.0.0.1:1935/live/001

拉流地址注意埠

本地測試可以使用VLC media player軟體