视频直播技术真的很难吗?手把手带你实现直播技术(一)

2021-01-18 19:41:35 1652

虚拟机的相关配置

  • 安装后记得开启ssh服务 sudo apt-get install openssh-server
  • 测试 sudo ps -e |grep ssh 或者 systemctl status sshd.service

相关服务版本(wget的时候已经声明版本号了)

服务器系统及中间件: ubuntu_18_04_x64 nginx-1.14 依赖以及相应版本: pcre-8.42 zlib-1.2.11 openssl-1.1.1a

安装相关服务

  • 在ubuntu18下载nginx,并下载nginx-http-flv-module nginx-http-flv-module是一个基于nginx-rtmp-module的流媒体服务器模块,除了具有nginx-rtmp-module所包含的所有功能之外,还具有以下特性
功能 nginx-http-flv-module nginx-rtmp-module 备注
HTTP-FLV (播放) x 支持HTTPS-FLV和chunked回复
GOP缓存 x
虚拟主机 x
省略listen配置 见备注 配置中必须有一个listen
纯音频支持 见备注 wait_videowait_key开启后无法工作
reuseport支持 x
定时打印访问记录 x
JSON风格的stat x

其他详情特性请参照项目GitHub页面

  • 下载相关服务和依赖(可能下载有点慢,我会把相关软件放到百度云供大家下载)
root@guofu:~/app# wget https://nginx.org/download/nginx-1.14.2.tar.gz
root@guofu:~/app# git clone https://github.com/winshining/nginx-http-flv-module.git
root@guofu:~/app# wget https://ftp.openssl.org/source/old/1.1.1/openssl-1.1.1a.tar.gz
root@guofu:~/app# wget  https://ftp.pcre.org/pub/pcre/pcre-8.42.tar.gz
root@guofu:~/app# wget https://zlib.net/fossils/zlib-1.2.11.tar.gz

  • 看一下当前目录下的文件
nginx-1.14.2  nginx-1.14.2.tar.gz  nginx-http-flv-module  openssl-1.1.1a  openssl-1.1.1a.tar.gz  pcre-8.42  pcre-8.42.tar.gz  zlib-1.2.1.1  zlib-1.2.1.1.tar.gz.1
  • 安装前解决依赖问题
sudo apt-get update
#安装依赖:gcc、g++依赖库
sudo apt-get install build-essential libtool
#安装 pcre依赖库(http://www.pcre.org/)
sudo apt-get install libpcre3 libpcre3-dev
#安装 zlib依赖库(http://www.zlib.net)
sudo apt-get install zlib1g-dev
#安装ssl依赖库
sudo apt-get install libssl-dev
  • 开始安装
root@guofu:~/app/nginx-1.14.2# ./configure --with-http_ssl_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-openssl=../openssl-1.1.1a --with-pcre=../pcre-8.42 --with-zlib=../zlib-1.2.11 --add-module=../nginx-http-flv-module

root@guofu:~/app/nginx-1.14.2# make 
root@guofu:~/app/nginx-1.14.2# make install
# 最后出现这些说明安装成功
objs/addon/nginx-http-flv-module/ngx_rtmp_stat_module.o \
objs/addon/nginx-http-flv-module/ngx_rtmp_control_module.o \
objs/addon/nginx-http-flv-module/ngx_http_flv_live_module.o \
objs/ngx_modules.o \
-ldl -lpthread -lcrypt ../pcre-8.42/.libs/libpcre.a ../openssl-1.1.1a/.openssl/lib/libssl.a ../openssl-1.1.1a/.openssl/lib/libcrypto.a -ldl -lpthread ../zlib-1.2.11/libz.a \
-Wl,-E
sed -e "s|%%PREFIX%%|/usr/local/nginx|" \
 -e "s|%%PID_PATH%%|/usr/local/nginx/logs/nginx.pid|" \
 -e "s|%%CONF_PATH%%|/usr/local/nginx/conf/nginx.conf|" \
 -e "s|%%ERROR_LOG_PATH%%|/usr/local/nginx/logs/error.log|" \
 < man/nginx.8 > objs/nginx.8
make[1]: Leaving directory '/root/app/nginx-1.14.2'
  • 修改配置文件
root@guofu:/usr/local/nginx/conf# pwd
/usr/local/nginx/conf
root@guofu:/usr/local/nginx/conf# vi nginx.conf
  • 安装完成后,切换到您的nginx工作目录下,找到配置文件打开(默认路径为/usr/local/nginx/conf/nginx.conf) 在末尾添加rtmp的配置信息
rtmp_auto_push on;
rtmp_auto_push_reconnect 1s;
rtmp_socket_dir /tmp;

rtmp {
    out_queue    4096;
    out_cork     8;
    max_streams  128;
    timeout      15s;

    log_interval 5s; #log模块在access.log中记录日志的间隔时间,对调试非常有用
    log_size     1m; #log模块用来记录日志的缓冲区大小


    server {
        listen 1935;
        server_name localhost; #用于虚拟主机名一致

        application myapp {
            live on;
            gop_cache on; #打开GOP缓存,减少首屏等待时间
        }

        application flv {
            live on;
            gop_cache on; #打开GOP缓存,减少首屏等待时间
        }

        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }

        application dash {
            live on;
            dash on;
            dash_path /tmp/dash;
        }
    }
}
  • 在http-server下添加location
location /live {
            flv_live on; #打开HTTP播放FLV直播流功能
            chunked_transfer_encoding on; #支持'Transfer-Encoding: chunked'方式回复

            add_header 'Access-Control-Allow-Origin' '*'; #添加额外的HTTP头
            add_header 'Access-Control-Allow-Credentials' 'true'; #添加额外的HTTP头
        }

#以下hls按照需求添加

location /hls {  #添加视频流存放地址。
         types {
             application/vnd.apple.mpegurl m3u8;
             video/mp2t ts;
         }
         #访问权限开启,否则访问这个地址会报403
         autoindex on;
         alias /usr/local/html/hls;#视频流存放地址,与上面的hls_path相对应,这里root和alias的区别可自行百度
         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';  
     }
  • 以下为技术小虫自己的nginx.conf
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

 location /live {
            flv_live on; #打开HTTP播放FLV直播流功能
            chunked_transfer_encoding on; #支持'Transfer-Encoding: chunked'方式回复

            add_header 'Access-Control-Allow-Origin' '*'; #添加额外的HTTP头
            add_header 'Access-Control-Allow-Credentials' 'true'; #添加额外的HTTP头
        }
 
 location /hls {  #添加视频流存放地址。
         types {
             application/vnd.apple.mpegurl m3u8;
             video/mp2t ts;
         }
         #访问权限开启,否则访问这个地址会报403
         autoindex on;
         alias /usr/local/html/hls;#视频流存放地址,与上面的hls_path相对应,这里root和alias的区别可自行百度
         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';  
     }

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

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

rtmp_auto_push on;
rtmp_auto_push_reconnect 1s;
rtmp_socket_dir /tmp;

rtmp {
    out_queue    4096;
    out_cork     8;
    max_streams  128;
    timeout      15s;

    log_interval 5s; #log模块在access.log中记录日志的间隔时间,对调试非常有用
    log_size     1m; #log模块用来记录日志的缓冲区大小


    server {
        listen 1935;
        server_name localhost; #用于虚拟主机名完全匹配

        application myapp {
            live on;
            gop_cache on; #打开GOP缓存,减少首屏等待时间
        }

        application flv {
            live on;
            gop_cache on; #打开GOP缓存,减少首屏等待时间
        }

        application hls {
            live on;
            hls on;
            hls_path /tmp/hls;
        }

        application dash {
            live on;
            dash on;
            dash_path /tmp/dash;
        }
    }
}
  • 启动nginx
root@guofu:/usr/local/nginx/sbin# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
root@guofu:/usr/local/nginx/sbin# curl 127.0.0.1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>

obs 的配置

  • 查看我的ip 172.16.131.131
root@guofu:/usr/local/nginx/sbin# ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.16.131.131  netmask 255.255.255.0  broadcast 172.16.131.255
        inet6 fe80::20c:29ff:fe4b:ab9e  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:4b:ab:9e  txqueuelen 1000  (Ethernet)
        RX packets 64541  bytes 71451732 (71.4 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 33213  bytes 5255173 (5.2 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 305  bytes 36645 (36.6 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 305  bytes 36645 (36.6 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

  • 先根据ip访问以下,确保ip是通的

  • 推流成功

观看直播

image.png
  • 最后贴上html 代码
<!doctype html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>flv.js demo</title>
    <style>
        .mainContainer {
            display: block;
            width: 1024px;
            margin-left: auto;
            margin-right: auto;
        }

        .urlInput {
            display: block;
            width: 100%;
            margin-left: auto;
            margin-right: auto;
            margin-top: 8px;
            margin-bottom: 8px;
        }

        .centeredVideo {
            display: block;
            width: 100%;
            height: 576px;
            margin-left: auto;
            margin-right: auto;
            margin-bottom: auto;
        }

        .controls {
            display: block;
            width: 100%;
            text-align: left;
            margin-left: auto;
            margin-right: auto;
        }
    </style>
</head>
<body>
<div class="mainContainer">
    <video id="videoElement" class="centeredVideo" controls autoplay width="1024" height="576">Your browser is too old which doesn't support HTML5 video.</video>
</div>
<br>
<div >
    <!--<button onclick="flv_load()">加载</button>-->
    <button onclick="flv_start()">开始</button>
    <button onclick="flv_pause()">暂停</button>
    <button onclick="flv_destroy()">停止</button>
    <input  type="text" name="seekpoint" />
    <button onclick="flv_seekto()">跳转</button>
</div>
<script src="http://bilibili.github.io/flv.js/dist/flv.js"></script>
<script>
    var player = document.getElementById('videoElement');
    if (flvjs.isSupported()) {
        var flvPlayer = flvjs.createPlayer({
            type: 'flv',
            "isLive": true,
            url: 'http://172.16.131.131/live?port=1935&app=myapp&stream=m',  //修改为您的url
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load(); //加载
        flv_start();
    }

    function flv_start() {
        player.play();
    }

    function flv_pause() {
        player.pause();
    }

    function flv_destroy() {
        player.pause();
        player.unload();
        player.detachMediaElement();
        player.destroy();
        player = null;
    }

    function flv_seekto() {
        player.currentTime = parseFloat(document.getElementsByName('seekpoint')[0].value);
    }
</script>
</body>

</html>

也可以通过播放器拉流

  • mac 使用vlc
  • windown 使用 potplayer 就可以,这里就不演示了

至此,一个简单的直播服务就完成了,当然,具体应用到实践中还需要关注其他的细节,下一篇文章会继续讲解