场景:HTML5页面需要通过<video>标签播放一段200M的服务器视频,默认会需要先下载完视频后才播放,有较长的等待时间;
解决方案:前端通过videojs-contrib-hlsjs.min.js来控制<video>标签进行播放m3u8视频流播放。
步骤:
1:服务端视频video.mp4生成video.ts视频数据包,执行如下命令://文章底部有ffmpeg相关说明
ffmpeg -y -i /deploys/html/statics/video/video.mp4 -vcodec copy -acodec copy -vbsf h264_mp4toannexb /deploys/html/statics/video/video.ts
2:对video.ts进行数据包分割,生成指定单位时长的数据包,这里设置成3秒时长的数据包,并生成数据包的目录文件:video.m3u8
ffmpeg -i /deploys/html/statics/video/video.ts -c copy -map 0 -f segment -segment_list /deploys/html/statics/video/video.m3u8 -segment_time 3 /deploys/html/statics/video/video-%03d.ts
3:前端引用://前后端自己约定video.m3u8的资源路径规则
<script type="text/javascript">
var default_hls_address = 'statics/video/video.m3u8';
var options = {
width: 1280,
height: 720,
poster: "statics/video/video.jpg",
autoplay: true,
controls: true,
loop: true,
preload: 'auto',
sourceOrder: true,
sources: [{
src: default_hls_address,
type: 'application/x-mpegURL'
}, {
src: '',
type: 'video/webm'
}],
techOrder: ['html5', 'flash'],
flash: {
swf: ''
}
}
var video = videojs('myvideo', options);
video.on(['loadstart', 'play', 'playing', 'firstplay', 'pause', 'ended', 'adplay', 'adplaying', 'adfirstplay', 'adpause', 'adended', 'contentplay', 'contentplaying', 'contentfirstplay', 'contentpause', 'contentended', 'contentupdate'], function(e) {
});
window.onbeforeunload=(e)=>{
video.dispose();
}
</script>
4:因为我生成的单个ts文件也有几百k大小,如果网络不好,会消耗一些时间,导致播放体验不好,所以开启了CDN服务,为ts文件提供CDN访问
注:
1: mp4生成ts数据包及m3u8文件,采用的ffmpeg工具及命令,可以参考文章:
videoJS报错:VIDEOJS: WARN: Player “myVideo” is already initialised. Options will not be applied.
//暂时没法解决,前端准备改vue写法解决;
目前我的做法:对访问的短链接地址跳转页面时,通过nginx动态生成时间戳参数来降低问题出现的几率:http://www.xxxx.com/szhgg 重定向 http://www.xxxx.com/html/index.html?t=1652351901.102
location ~ ^/szhgg {
set $t $msec;
rewrite ^/ "/html/index.html?t=$t" permanent;
}