vue实现音乐上下曲
Vue实现音乐上下曲功能
基本思路
音乐播放器上下曲功能需要维护一个播放列表和当前播放索引。通过索引增减实现切换,同时考虑列表循环、随机播放等模式。
核心代码实现
1. 数据准备
data() {
return {
playlist: [
{ id: 1, title: '歌曲1', src: '/music/1.mp3' },
{ id: 2, title: '歌曲2', src: '/music/2.mp3' },
{ id: 3, title: '歌曲3', src: '/music/3.mp3' }
],
currentIndex: 0,
playMode: 'order' // order|loop|random
}
}
2. 上一曲方法
methods: {
prevSong() {
if (this.playMode === 'random') {
this.currentIndex = Math.floor(Math.random() * this.playlist.length)
} else {
this.currentIndex--
if (this.currentIndex < 0) {
this.currentIndex = this.playMode === 'loop'
? this.playlist.length - 1
: 0
}
}
this.playCurrent()
}
}
3. 下一曲方法
nextSong() {
if (this.playMode === 'random') {
this.currentIndex = Math.floor(Math.random() * this.playlist.length)
} else {
this.currentIndex++
if (this.currentIndex >= this.playlist.length) {
this.currentIndex = this.playMode === 'loop'
? 0
: this.playlist.length - 1
}
}
this.playCurrent()
}
4. 播放当前歌曲
playCurrent() {
const audio = this.$refs.audioPlayer
audio.src = this.playlist[this.currentIndex].src
audio.load()
audio.play().catch(e => console.log('播放错误:', e))
}
模板示例
<template>
<div>
<audio ref="audioPlayer"></audio>
<button @click="prevSong">上一曲</button>
<button @click="nextSong">下一曲</button>
<p>当前播放: {{ playlist[currentIndex].title }}</p>
</div>
</template>
进阶功能
自动切换下一曲 监听audio元素的ended事件:
mounted() {
this.$refs.audioPlayer.addEventListener('ended', this.nextSong)
}
播放模式切换
switchMode() {
const modes = ['order', 'loop', 'random']
const current = modes.indexOf(this.playMode)
this.playMode = modes[(current + 1) % modes.length]
}
注意事项
- 需要处理音频加载错误情况
- 移动端需注意自动播放限制
- 实际项目中可能需要加入Vuex管理状态
- 考虑添加播放进度条、音量控制等配套功能







