阿里云实践 - HTML5断点播放m3u8视频(videojs)

场景: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工具及命令,可以参考文章:

linux下安装ffmpeg的详细教程_Mr·wong的博客-CSDN博客_ffmpeg linux一、centos linux下安装ffmpeg1、下载解压12wget http://www.ffmpeg.org/releases/ffmpeg-3.1.tar.gztar-zxvf ffmpeg-3.1.tar.gz2、 进入解压后目录,输入如下命令/usr/local/ffmpeg为自己指定的安装目录1234cdffmpeg-3.1./configu..https://blog.csdn.net/weixin_39412946/article/details/110426738        2:二次进入页面的时候,可能会出现错误: 

videoJS报错:VIDEOJS: WARN: Player “myVideo” is already initialised. Options will not be applied.

      参考其它文章:videoJS报错:VIDEOJS: WARN: Player “myVideo” is already initialised. Options will not be applied._weixin_45115895的博客-CSDN博客videoJS报错:VIDEOJS: WARN: Player “myVideo” is already initialised. Options will not be applied.移动端vue项目商品详情页有用到视频播放器,刚进入时没有错误,进入到其他页面再返回到商品详情页就会出现视频缩小到了左上角,且不能再播放了,查看控制台发现报了一个警告VIDEOJS: WARN: Player “myVideo” is already initialised. Options will not be aphttps://blog.csdn.net/weixin_45115895/article/details/106526981

      //暂时没法解决,前端准备改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;
}

猜你喜欢

转载自blog.csdn.net/WJL_MGQS/article/details/124737114