阿里云实践 - HTML5断点播放m3u8视频(videojs)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
场景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;
}