vue2 使用 vue-video-player 播放m3u8 流地址视频

本文介绍了如何在Vue项目中安装并配置vue-video-player和videojs-contrib-hls插件,以支持HLS流文件播放,包括设置aspectRatio和使用常见API方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装插件  :

注意需要引入  videojs-contrib-hls ,否则无法播放hls流文件 

npm install vue-video-player@5.0.1 --save
npm install videojs-contrib-hls@5.15.0 --save

main.js 引入

require('vue-video-player/src/custom-theme.css')
require('video.js/dist/video-js.css')
import VideoPlayer from 'vue-video-player'
import hls from "videojs-contrib-hls"; 

Vue.use(VideoPlayer)
Vue.use(hls);

代码内引入:

注意点:   

1.type: 'application/x-mpegURL' ,否则无法播放流文件 

2.aspectRatio: '16:9',  宽高比需要进行设置, 若没有进行设置,会出现黑边过高或者过宽的问题

<video-player ref="videoPlayer" :options="playerOptions" class="video-player vjs-custom-skin"/>


playerOptions: {
        autoplay: true,
        hls:true,
        aspectRatio: '16:9',
        fluid: false, 
        sources: [
          {
            src: '',
            // type: 'video/mu38'
            type: 'application/x-mpegURL'
          }
        ],
      },

常用API方法:

// 加载视频
this.$refs.videoPlayer.player.load();
// 播放视频
this.$refs.videoPlayer.player.play();
// 暂停播放
this.$refs.videoPlayer.player.pause();
// 直接全屏 如果当前设备支持的话
this.$refs.videoPlayer.player.requestFullscreen();

### Vue项目中使用vue-video-player播放M3U8视频文件时遇到的播放失败解决方案 为了成功在Vue项目中通过`vue-video-player`组件播放M3U8格式的视频,需确保已正确配置并引入必要的依赖库。由于单独的`vue-video-player`并不直接支持M3U8格式,因此还需要额外安装`videojs-contrib-hls`来提供HLS协议的支持[^1]。 #### 安装必要依赖包 首先,在命令行工具中执行如下npm指令以安装所需的软件包: ```bash npm install video.js vue-video-player videojs-contrib-hls --save ``` 这一步骤会下载并保存`video.js`, `vue-video-player`以及专门用于处理HLS流媒体传输的插件`videojs-contrib-hls`到项目的node_modules目录下。 #### 配置Video Player选项 接着,在Vue组件内部定义好`playerOptions`属性,指定要使用播放源及其类型为application/x-mpegURL(即M3U8)。同时,记得给定其他可能影响正常工作的参数设置,比如自动播放(`autoplay`)、循环播放(`loop`)等特性开关。 ```javascript data() { return { playerOptions: { autoplay: false, loop: true, controls: true, // 显示控制条 sources: [{ src: 'https://yourdomain.com/path/to/playlist.m3u8', type: "application/x-mpegURL" }], techOrder: ["html5", "flash"], flash: { hls: { withCredentials: false } }, html5: { hls: { overrideNative: true }} } }; } ``` 上述代码片段中的`src`字段应替换为目标M3U8文件的实际网络地址;而`techOrder`数组指定了优先采用的技术栈顺序——这里设为首选HTML5技术实现播放功能,并启用覆盖原生浏览器行为的功能以便更好地兼容不同设备上的表现差异。 #### HTML模板部分 最后,在.vue文件内的template标签里加入对应的<video-player>标记符,绑定之前准备好的`playerOptions`对象作为其`:options`属性值即可完成基本布局构建工作。 ```html <template> <div id="app"> <!-- Video Player --> <video-player class="vjs-custom-skin" :options="playerOptions"></video-player> </div> </template> <script> // 导入相关模块... import { videoPlayer } from 'vue-video-player' export default { name: 'App', components: { videoPlayer }, data(){ ... } }; </script> ``` 以上操作完成后重新启动开发服务器测试页面效果,如果一切顺利的话应该能够看到可以正常加载和播放M3U8资源的多媒体控件了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值