Vue rtsp/rtmp/m3u8/??低晹z像頭,實時推流、視頻播放解決方案

預(yù)覽圖

1、前言

本方案為vue2項目,可分為前端和服務(wù)端,這里主要重點說一下服務(wù)端,服務(wù)端使用的是WebSocket服務(wù),根據(jù)ffmpeg工具實現(xiàn)實時轉(zhuǎn)流,對實時流進行格式轉(zhuǎn)換輸出flv格式,前端使用flv.js插件播放flv格式的視頻,如果沒有安裝ffmpeg工具,請先安裝!點擊去ffmpeg官網(wǎng)下載

截至發(fā)布日期可用的視頻地址:
海外地址(速度慢):rtmp://ns8.indexforce.com/home/mystream
cctv央視網(wǎng):https://cctvwbndbd.a.bdydns.com/cctvwbnd/cctv1_2/index.m3u8?BR=single
m3u8格式視頻:https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8

2、服務(wù)端

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

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

代碼(serve/index.js)如下,這里運行服務(wù)的轉(zhuǎn)流地址為ws://localhost:8888,前端需要使用這個地址進行實時轉(zhuǎn)流

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

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

// 監(jiān)聽連接
wss.on('connection', handleConnection)

// 連接時觸發(fā)事件
function handleConnection (ws, req) {
  // 獲取前端請求的流地址(前端websocket連接時后面帶上流地址)
  const url = req.url.slice(1)
  // 傳入連接的ws客戶端 實例化一個流
  const stream = webSocketStream(ws, { binary: true })
  // 通過ffmpeg命令 對實時流進行格式轉(zhuǎn)換 輸出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 {
    // 執(zhí)行命令 傳輸?shù)綄嵗髦蟹祷亟o客戶端
    ffmpegCommand.pipe(stream)
  } catch (error) {
    console.log(error)
  }
}

3、前端

前端主要使用flv.js,播放服務(wù)端實時輸出的flv格式視頻,該插件是由B站(bilibili.com)使用原生JavaScript開發(fā),并沒有用到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)安裝并在頁面導(dǎo)入flv.js

安裝flv.js

npm install flv.js --save

頁面導(dǎo)入flv.js

import flvjs from 'flv.js';
(3)使用flv.js創(chuàng)建video視頻并播放。使用服務(wù)端轉(zhuǎn)流地址ws://localhost:8888/ + 推流地址URL對實時流轉(zhuǎn)為flv格式并播放,具體接口文檔請查看flv.js API
// 創(chuàng)建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"
}
服務(wù)端運行:
npm run start
前端運行:
npm run serve

5、完整代碼

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容