使用Vue播放M3U8视频流的方法
安装依赖
需要安装video.js和videojs-contrib-hls插件,用于解析和播放M3U8格式的视频流。
npm install video.js videojs-contrib-hls引入并初始化Video.js
在Vue组件中引入Video.js及相关样式,初始化播放器并配置HLS支持。
importvideojsfrom'video.js'import'video.js/dist/video-js.css'import'videojs-contrib-hls'exportdefault{mounted(){this.initVideoPlayer()},methods:{initVideoPlayer(){this.player=videojs(this.$refs.videoPlayer,{autoplay:true,controls:true,sources:[{src:'your-m3u8-url.m3u8',type:'application/x-mpegURL'}]})}},beforeDestroy(){if(this.player){this.player.dispose()}}}模板部分
在模板中添加video标签作为播放器容器,需设置data-setup属性为空对象以启用Video.js初始化。
<template><div><videoref="videoPlayer"class="video-js vjs-default-skin"width="640"height="360"data-setup="{}"></video></div></template>样式调整
.video-js{width:100%;max-width:640px;margin:0 auto;}通过CSS调整播放器尺寸和外观,确保适应页面布局。
注意事项
确保M3U8视频流地址可跨域访问,或配置服务器CORS策略。
移动端可能需要添加playsinline属性以实现内联播放。
若使用HTTPS环境,需确保视频流地址同为HTTPS。
完整组件示例
<template><divclass="video-container"><videoref="videoPlayer"class="video-js"></video></div></template><script>importvideojsfrom'video.js'import'video.js/dist/video-js.css'import'videojs-contrib-hls'exportdefault{props:{src:{type:String,required:true}},mounted(){this.initPlayer()},methods:{initPlayer(){this.player=videojs(this.$refs.videoPlayer,{autoplay:false,controls:true,sources:[{src:this.src,type:'application/x-mpegURL'}]})}},beforeDestroy(){if(this.player){this.player.dispose()}}}</script><stylescoped>.video-container{margin:20px auto;width:80%;}</style>替代方案(使用hls.js)
若需更轻量级方案,可使用hls.js库直接处理M3U8流。
安装hls.js
npminstallhls.js实现代码
importHlsfrom'hls.js'exportdefault{data(){return{hls:null}},mounted(){this.loadVideo()},methods:{loadVideo(){constvideoSrc='your-m3u8-url.m3u8'constvideo=this.$refs.videoPlayerif(Hls.isSupported()){this.hls=newHls()this.hls.loadSource(videoSrc)this.hls.attachMedia(video)}elseif(video.canPlayType('application/vnd.apple.mpegurl')){video.src=videoSrc}}},beforeDestroy(){if(this.hls){this.hls.destroy()}}}