vue实现歌曲循环
Vue 实现歌曲循环播放
使用 audio 标签和 Vue 数据绑定
在 Vue 中可以通过 audio 标签的 loop 属性实现单曲循环。以下是一个基础实现示例:

<template>
<div>
<audio ref="audioPlayer" :src="currentSong.url" @ended="handleEnded" loop></audio>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
</div>
</template>
<script>
export default {
data() {
return {
currentSong: {
url: 'path/to/song.mp3'
},
isPlaying: false
}
},
methods: {
togglePlay() {
const audio = this.$refs.audioPlayer
this.isPlaying ? audio.pause() : audio.play()
this.isPlaying = !this.isPlaying
},
handleEnded() {
// 循环逻辑已通过loop属性实现
}
}
}
</script>
实现播放列表循环
如果需要实现播放列表的循环播放,可以通过监听 ended 事件切换歌曲:

<template>
<div>
<audio ref="audioPlayer" :src="currentSong.url" @ended="nextSong"></audio>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
<button @click="nextSong">下一首</button>
</div>
</template>
<script>
export default {
data() {
return {
songs: [
{ url: 'song1.mp3' },
{ url: 'song2.mp3' },
{ url: 'song3.mp3' }
],
currentIndex: 0,
isPlaying: false
}
},
computed: {
currentSong() {
return this.songs[this.currentIndex]
}
},
methods: {
togglePlay() {
const audio = this.$refs.audioPlayer
this.isPlaying ? audio.pause() : audio.play()
this.isPlaying = !this.isPlaying
},
nextSong() {
this.currentIndex = (this.currentIndex + 1) % this.songs.length
if (this.isPlaying) {
this.$nextTick(() => {
this.$refs.audioPlayer.play()
})
}
}
}
}
</script>
添加循环模式切换
可以实现多种循环模式(单曲循环/列表循环/随机播放):
<template>
<div>
<audio ref="audioPlayer" :src="currentSong.url" @ended="handleEnded"></audio>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
<button @click="changeMode">
模式: {{ ['列表循环', '单曲循环', '随机播放'][mode] }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
songs: [
{ url: 'song1.mp3' },
{ url: 'song2.mp3' },
{ url: 'song3.mp3' }
],
currentIndex: 0,
isPlaying: false,
mode: 0 // 0:列表循环 1:单曲循环 2:随机播放
}
},
computed: {
currentSong() {
return this.songs[this.currentIndex]
}
},
methods: {
togglePlay() {
const audio = this.$refs.audioPlayer
this.isPlaying ? audio.pause() : audio.play()
this.isPlaying = !this.isPlaying
},
changeMode() {
this.mode = (this.mode + 1) % 3
},
handleEnded() {
if (this.mode === 1) {
this.$refs.audioPlayer.play()
return
}
if (this.mode === 2) {
this.currentIndex = Math.floor(Math.random() * this.songs.length)
} else {
this.currentIndex = (this.currentIndex + 1) % this.songs.length
}
if (this.isPlaying) {
this.$nextTick(() => {
this.$refs.audioPlayer.play()
})
}
}
}
}
</script>
使用第三方库
如果需要更强大的音频控制功能,可以考虑使用第三方库如 howler.js:
import { Howl } from 'howler'
export default {
data() {
return {
player: null,
currentSong: { url: 'song1.mp3' }
}
},
methods: {
initPlayer() {
this.player = new Howl({
src: [this.currentSong.url],
loop: true,
autoplay: false
})
},
togglePlay() {
if (this.player.playing()) {
this.player.pause()
} else {
this.player.play()
}
}
},
mounted() {
this.initPlayer()
}
}
以上方法提供了不同复杂度的歌曲循环实现方案,可根据具体需求选择适合的方式。






