Nginx-http-flv-module使用

Nginx-http-flv-module使用

在之前的项目中,我使用了VLC插件来播放海康的摄像头视频,但是需要浏览器支持NPAPI插件,当时使用的是Firefox 50.1.0,使用这么旧的版本很难受。。。想找一个原生支持视频播放的方法在新版本的浏览器上使用。

在网上搜索一下,发现大部分的方法是使用ffmepgRTMP流转为FLV流,配合Bilibili的flv.js来实现无插件播放

nginx-http-flv-module 使用

使用源码编译安装的方式,nginx编译之前有写,参考那里,nginx-http-flv-module编译无非加上一句

./configure --add-module=/path/to/nginx-http-flv-module

配置 nginx.conf

# RTMP块
rtmp {
     server {
        listen 1935;
        chunk_size 4000;

        # Transcoding(ffmpeg need)
        application pull {
           live on;
           exec ffmpeg -re -i rtmp://localhost:1935/$app/$name -c copy -f flv rtmp://localhost:1935/flv/${name};
        }
        application flv {
           live on;
        }
     }
}

这里监听1935端口,视频源应当推流到 rtmp://ip:1935/pull/{$name}$name可以自定义。此配置还同时启动了ffmpegrtmp转为flv并推送到application flv处。

配置sites-available目录内的server.conf

我这里创建了一个live.conf

server {
    listen 80;
    server_name localhost;

    location /stat {
        # 推流播放和录制统计数据的配置
        rtmp_stat all;
        rtmp_stat_stylesheet stat.xsl;
    }

    location /stat.xsl {
        root /etc/nginx-http-flv-module/; # 指定 stat.xsl 的位置
    }

    location /live {
        flv_live on; # 打开 HTTP 播放 FLV 直播流功能
        chunked_transfer_encoding on; #支持 'Transfer-Encoding: chunked' 方式回复
        add_header 'Access-Control-Allow-Origin' '*';  # 避免CORS跨域被阻止
        add_header 'Access-Control-Allow-Credentials' 'true';
    }
}

这里定义一个localhost服务器,/stat用来查看http-flv-module状态, /stat.xsl中的nginx-http-flv-module(就是下载来的源码)不要放在root目录下

flv.js 使用

安装npm apt-get install npm -y 首次使用npm时需要先npm init -f否则会提示缺少package.json文件

安装flv.js

npm install --save flv.js

在当前用户目录下找到node_modules在里面就有了flv.js目录

在页面上使用

<script src="../flv.min.js"></script>
<video id="videoElement"></video>
<script>
    if (flvjs.isSupported()) {
        var videoElement = document.getElementById('videoElement');
        var flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: 'http://example.com/flv/video.flv'
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
    }
</script>

其中的url改成

http://localhost/live?port=1935&app=flv&stream=mystream

参数详解:

  • live : server 中的 location /live
  • port : rtmplisten
  • app :rtmpapplication flv
  • stream:自定义,需要和推流中的{$name}相同

之后即可在网页中直接查看直播了。


参考资料:

GitHub - winshining/nginx-http-flv-module: Media streaming server based on nginx-rtmp-module. In addtion to the features nginx-rtmp-module provides, HTTP-FLV, GOP cache and VHOST (one IP for multi domain names) are supported now.

GitHub - bilibili/flv.js: HTML5 FLV Player

npm install模块时 报错:not such file or directory。是何原因? - SegmentFault 思否

Nginx与Nginx-rtmp-module搭建RTMP视频直播和点播服务器 - 知乎 (zhihu.com)