解决HTML5 video不支持播放m3u8格式视频的方法

m3u8是一种基于HLS(HTTP Live Streaming)文件视频格式,HLS由苹果公司提出,使用<video></video>标签可以在Safari浏览器直接播放,但其它浏览器要借助hls.js或基于hls.js开发的html5播放器插件才能兼容播放m3u8格式视频,否则会提示不支持视频格式。

基础代码

HTML代码:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<video id="video1" controls></video>

提示:建议把hls.js下载到本地引用

JS代码:

var _videoDom = document.getElementById('video1');
var _videoURL = 'https://www.tddx.net/video.m3u8';	//视频URL
if(Hls.isSupported()){
	var hls = new Hls();
	hls.loadSource(_videoURL);
	hls.attachMedia(_videoDom);
	hls.on(Hls.Events.MANIFEST_PARSED,function(){
		_videoDom.play();
	});	
}

扩展使用

HTML代码:

<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<div class="list">
	<ul>
		<li data-id="1" data-video="https://www.tddx.net/video.m3u8">
			<div class="video"></div>
			<div class="play"></div>
			<div class="close"></div>
		</li>
		<li data-id="2" data-video="https://www.tddx.net/video.m3u8">
			<div class="video"></div>
			<div class="play"></div>
			<div class="close"></div>
		</li>
	</ul>
</div>

JS代码:

$('.play').click(function(){
	var _this = $(this).parents('li');
	var _videoID = _this.attr('data-id');
	var _videoURL = _this.attr('data-video');
	var _videoHTML = '<video src="'+_videoURL+'" id="video'+_videoID+'" controls></div>';
	_this.find('.video').show().html(_videoHTML);
	var _videoDom = document.getElementById('video'+_videoID);								
	if(Hls.isSupported()){
		var hls = new Hls();
		hls.loadSource(_videoURL);
		hls.attachMedia(_videoDom);
		hls.on(Hls.Events.MANIFEST_PARSED,function(){
			_videoDom.play();
		});		
	}
	_this.find('.close').click(function(){
		_this.find('.video').hide().find('video').remove();
	});
});

基于hls.js插件:

Video.js:videojs-contrib-hls.js

Flowplayer:flowplayer-hls.js

hls.js项目地址

Github:https://github.com/video-dev/hls.js

关键词: video标签