最近开发中遇到一个网页需要连接监控查看的功能,要求播放实时播放.flv文件,我通过查找找到的两个可以使用的插件video.js和flv.js,flv.js是当前b站正在使用的插件基于JavaScript开发h5插件。
好了,我们继续开始操作吧!首先我从github下flv里clone下文件
附上链接https://github.com/bilibili/flv.js.git
然后我们进行构建代码
npm install使用npm或cnpm都可以,构建好了我们发现多出node_modules文件,接着我们安装安装生成工具:
npm install -g gulp生成工具完成后进行打包压缩
gulp release在打包时我遇到了一个问题
const { Math, Object } = primordials;它这段代码报错了。。。,它竟然报错了。。
然后在网上找到原因是因为node的版本不对。。。我用的是v12.3.1版本,而它需要v10.X.X版本,所以我使用gnvm进行下载v10.1.0版本,gnvm是node的版本管理工具可以了解一下
然后我们在执行gulp release,发现没问题,打开文件目录,就发现dist文件夹,里面有flv.js和flv.min.js文件,我取得是flv.min.js文件,当然里面有播放视频的demo可以参考下。在这里我附上我的代码,playurl是flv文件地址
<video id="videoElement" class="centeredVideo" controls autoplay> Your browser is too old which doesn't support HTML5 video. </video> /*新加*/ getvideoinfo(fIp){ // 获取视频流 let _this = this getvideoinfo({fIp:fIp}).then(res => { _this.getvideoheartbeat(fIp) //心跳 _this.playurl = res.data.data //地址 _this.flv_load(res.data.data) //调用 _this.correctvideo() //实时更新 ,也可以修改下放心跳里 }) }, getvideoheartbeat(fIp){ //video心跳 let _this = this getvideoheartbeat({fIp:fIp}) var currenttime = Math.floor(document.getElementsByClassName('centeredVideo'+_this.videoid) [0].currentTime); // 每5秒请求一次 _this.closeTimeout = window.setTimeout(() => { _this.getvideoheartbeat(fIp) }, 5000); }, /*新加*/ flv_load(playurl) { var _this = this if (flvjs.isSupported()) { _this.videoElement = document.getElementById('videoElement'); _this.flvPlayer = flvjs.createPlayer({ type: 'flv', url: playurl, isLive: true, cors: true, enableWorker: true, enableStashBuffer: false, stashInitialSize: 128, autoCleanupSourceBuffer:true }); _this.flvPlayer.attachMediaElement(_this.videoElement); _this.flvPlayer.load(); _this.flvPlayer.play(); } }, cancelplay() { var _this = this _this.flvPlayer.pause(); _this.flvPlayer.unload(); _this.flvPlayer.detachMediaElement(); _this.flvPlayer.destroy(); _this.flvPlayer = null; },矫正实时播放,稍微改了下,不一定对,原理是读取视频预存,当 当前进度和预存最新时间相差大于0.15时,快进当前时间,每隔10秒执行一次
correctvideo(){ var _this = this // 矫正实时播放速度 if (_this.videoElement) { let buffered = _this.videoElement.buffered if (buffered.length > 0) { let end = buffered.end(0) if (end - _this.videoElement.currentTime > 0.15) { _this.videoElement.currentTime = end - 1 // console.log('changecurrentTime'+_this.videoElement.currentTime); } } } _this.tocorrectvideo= window.setTimeout(() => { _this.correctvideo() }, 100000); },希望对你们有用!