Html播放m3u8视频
一,首先现在hls.js
hls.js
二,html代码
<video id="video" webkit-playsinline playsinline x5-playsinline controlswidth="100%" height="100%"poster="/statics/video/poster.png">您的浏览器不支持视频播放
</video>
<script src="/statics/js/hls.js"></script>
<script>document.addEventListener('DOMContentLoaded', function() {const video = document.getElementById('video');// 视频源地址const videoSrc = "/statics/video/jzauntexam.m3u8";// 初始化 HLS 播放器function initHls() {if (Hls.isSupported()) {const hls = new Hls({enableWorker: true,lowLatencyMode: true,backBufferLength: 90});hls.loadSource(videoSrc);hls.attachMedia(video);hls.on(Hls.Events.MANIFEST_PARSED, function(event, data) {console.log('HLS manifest parsed', data);// 尝试自动播放//attemptPlay();});hls.on(Hls.Events.MEDIA_ATTACHED, function() {console.log('HLS media attached');});hls.on(Hls.Events.ERROR, function(event, data) {console.error('HLS error:', data);handleError(data);});hls.on(Hls.Events.MEDIA_ATTACHING, function() {console.log('HLS media attaching');});}// Safari 浏览器原生支持 HLSelse if (video.canPlayType('application/vnd.apple.mpegurl')) {video.src = videoSrc;video.addEventListener('loadedmetadata', function() {console.log('Safari HLS loaded');// 尝试自动播放//attemptPlay();});video.addEventListener('error', function(e) {console.error('Safari HLS error:', e);});}// 不支持 HLS 的情况else {console.error('HLS is not supported in this browser');alert('您的浏览器不支持播放该视频格式');}}// 尝试自动播放function attemptPlay() {const playPromise = video.play();if (playPromise !== undefined) {playPromise.then(() => {console.log('自动播放成功');}).catch(error => {console.log('自动播放被阻止:', error);});}}// 错误处理function handleError(error) {if (error.type === Hls.ErrorTypes.MEDIA_ERROR) {console.warn('media error encountered, try to recover');}if (error.fatal) {switch(error.type) {case Hls.ErrorTypes.NETWORK_ERROR:console.log('network error');break;case Hls.ErrorTypes.MEDIA_ERROR:console.log('media error');break;default:console.log('other error');}}}// 初始化 HLSinitHls();// 事件监听video.addEventListener('waiting', () => {});video.addEventListener('playing', () => {});video.addEventListener('timeupdate', ()=>{//监听播放进度if (video.currentTime > 0 && video.currentTime >= video.duration){app.ksbtndisable = false;}});});
</script>