返回
用Vue.js播放视频的三种方法
前端
2023-11-12 06:07:35
前言
本文将介绍三种在Vue.js中使用videojs播放视频的方法,包括基本的自动播放、换台,以及如何解决视频无法自动播放或报错DOMException: play() failed muted="false"的问题。
方法一:基本的自动播放
<template>
<div>
<video-js id="my-video"
ref="videoRef"
:options="playerOptions"
@ready="handleReady">
</video-js>
</div>
</template>
<script>
import videojs from 'video.js'
export default {
data() {
return {
playerOptions: {
autoplay: true,
controls: true,
sources: [
{
src: 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
type: 'video/mp4'
}
]
}
}
},
methods: {
handleReady() {
const player = this.$refs.videoRef.player
player.play()
}
}
}
</script>
方法二:换台
<template>
<div>
<select v-model="selectedChannel">
<option value="channel-1">Channel 1</option>
<option value="channel-2">Channel 2</option>
<option value="channel-3">Channel 3</option>
</select>
<video-js id="my-video"
ref="videoRef"
:options="playerOptions">
</video-js>
</div>
</template>
<script>
import videojs from 'video.js'
export default {
data() {
return {
selectedChannel: 'channel-1',
playerOptions: {
autoplay: true,
controls: true,
sources: [
{
src: 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
type: 'video/mp4'
},
{
src: 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8',
type: 'video/mp4'
},
{
src: 'https://bitdash-a.akamaihd.net/content/art-of-motion_dash/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
type: 'video/mp4'
}
]
}
}
},
watch: {
selectedChannel(val) {
const player = this.$refs.videoRef.player
player.src({
src: this.playerOptions.sources[val].src,
type: this.playerOptions.sources[val].type
})
player.play()
}
}
}
</script>
方法三:解决视频无法自动播放或报错DOMException: play() failed muted="false"的问题
<template>
<div>
<video-js id="my-video"
ref="videoRef"
:options="playerOptions"
@ready="handleReady">
</video-js>
</div>
</template>
<script>
import videojs from 'video.js'
export default {
data() {
return {
playerOptions: {
autoplay: true,
controls: true,
muted: false,
sources: [
{
src: 'https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
type: 'video/mp4'
}
]
}
}
},
methods: {
handleReady() {
const player = this.$refs.videoRef.player
player.play()
}
}
}
</script>
在上面的代码中,我们设置了muted: false,表示视频不用静音(视频播放便有声音),这样就可以解决视频无法自动播放或报错DOMException: play() failed muted="false"的问题。
总结
本文介绍了三种在Vue.js中使用videojs播放视频的方法,包括基本的自动播放、换台,以及如何解决视频无法自动播放或报错DOMException: play() failed muted="false"的问题。希望本文对您有所帮助。