Vue rtsp/rtmp/m3u8/海康威视摄像头,实时推流、视频播放解决方案

预览图

1、前言

本方案为vue2项目,可分为前端和服务端,这里主要重点说一下服务端,服务端使用的是WebSocket服务,根据ffmpeg工具实现实时转流,对实时流进行格式转换输出flv格式,前端使用flv.js插件播放flv格式的视频,如果没有安装ffmpeg工具,请先安装!点击去ffmpeg官网下载

截至发布日期可用的视频地址:
海外地址(速度慢):rtmp://ns8.indexforce.com/home/mystream
cctv央视网:https://cctvwbndbd.a.bdydns.com/cctvwbnd/cctv1_2/index.m3u8?BR=single
m3u8格式视频:https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8

2、服务端

安装如下依赖包,其中fluent-ffmpeg是基于ffmpeg工具命令的

npm install fluent-ffmpeg ws websocket-stream --save

代码(serve/index.js)如下,这里运行服务的转流地址为ws://localhost:8888,前端需要使用这个地址进行实时转流

const WebSocket = require('ws')
const webSocketStream = require('websocket-stream/stream')
const ffmpeg = require('fluent-ffmpeg')

// 建立WebSocket服务
const wss = new WebSocket.Server({ port: 8888, perMessageDeflate: false })

// 监听连接
wss.on('connection', handleConnection)

// 连接时触发事件
function handleConnection (ws, req) {
  // 获取前端请求的流地址(前端websocket连接时后面带上流地址)
  const url = req.url.slice(1)
  // 传入连接的ws客户端 实例化一个流
  const stream = webSocketStream(ws, { binary: true })
  // 通过ffmpeg命令 对实时流进行格式转换 输出flv格式
  const ffmpegCommand = ffmpeg(url)
    .addInputOption('-analyzeduration', '100000', '-max_delay', '1000000')
    .on('start', function () { console.log('Stream started.') })
    .on('codecData', function () { console.log('Stream codecData.') })
    .on('error', function (err) {
      console.log('An error occured: ', err.message)
      stream.end()
    })
    .on('end', function () {
      console.log('Stream end!')
      stream.end()
    })
    .outputFormat('flv').videoCodec('copy')
    // .outputFormat('flv').videoCodec('copy').noAudio() // 取消音频输出

  stream.on('close', function () {
    ffmpegCommand.kill('SIGKILL')
  })

  try {
    // 执行命令 传输到实例流中返回给客户端
    ffmpegCommand.pipe(stream)
  } catch (error) {
    console.log(error)
  }
}

3、前端

前端主要使用flv.js,播放服务端实时输出的flv格式视频,该插件是由B站(bilibili.com)使用原生JavaScript开发,并没有用到Flash。

(1)HTML
<div class="video-wrap">
    <div class="input-wrap">
        <input v-model="url" placeholder="请输入视频地址, 支持rtsp/rtmp格式"></input>
        <button @click="onPlay">播放</button>
    </div>
    <video
        muted="muted"
        controls
        width="100%"
        height="600"
        ref="video"
    ></video>
</div>

(2)安装并在页面导入flv.js

安装flv.js

npm install flv.js --save

页面导入flv.js

import flvjs from 'flv.js';
(3)使用flv.js创建video视频并播放。使用服务端转流地址ws://localhost:8888/ + 推流地址URL对实时流转为flv格式并播放,具体接口文档请查看flv.js API
// 创建video
createVideo() {
    if (flvjs.isSupported()) {
        const videoElement = this.$refs.video;
        this.flvPlayer = flvjs.createPlayer(
            {
                type: 'flv',
                // isLive: false,
                // hasAudio: false,
                url: 'ws://localhost:8888/' + this.url
            },
            {
                cors: true, // 是否跨域
                // enableWorker: true, // 是否多线程工作
                enableStashBuffer: false, // 是否启用缓存
                // stashInitialSize: 128, // 缓存大小(kb)  默认384kb
                autoCleanupSourceBuffer: true, // 是否自动清理缓存
                fixAudioTimestampGap: false //false才会音视频同步
            }
        );
        this.flvPlayer.attachMediaElement(videoElement);
        this.flvPlayer.load();
        this.flvPlayer.play();
        // 报错重连
        this.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
            console.log('errorType:', errType);
            console.log('errorDetail:', errDetail);
            this.play()
        });
    }
},
// 销毁video
destoryVideo() {
    if(this.flvPlayer){
        this.flvPlayer.pause();
        this.flvPlayer.unload();
        this.flvPlayer.detachMediaElement();
        this.flvPlayer.destroy();
        this.flvPlayer = null;
    }
},
// 重播/播放
play(){
    this.destoryVideo();
    this.createVideo();
}

4、运行

tips:在根目录打开两个命令窗口分别运行。

package.json配置:
"scripts": {
    "serve": "vue-cli-service serve",
    "start": "node serve/index.js",
    "build": "vue-cli-service build"
},
"dependencies": {
    "core-js": "^2.6.5",
    "fluent-ffmpeg": "^2.1.2",
    "flv.js": "^1.6.2",
    "vue": "^2.6.10",
    "websocket-stream": "^5.5.2",
    "ws": "^8.13.0"
}
服务端运行:
npm run start
前端运行:
npm run serve

5、完整代码

源码地址:https://gitee.com/jias0606/stream-to-video

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容