vue实现音乐播放
Vue 实现音乐播放功能
核心实现步骤
音频元素与播放控制
在 Vue 组件中使用 <audio> 元素并绑定 ref,通过 JavaScript 控制播放状态:
<template>
<audio ref="audioPlayer" :src="currentSong.url"></audio>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
</template>
<script>
export default {
data() {
return {
currentSong: { url: 'music.mp3' },
isPlaying: false
}
},
methods: {
togglePlay() {
const player = this.$refs.audioPlayer
this.isPlaying ? player.pause() : player.play()
this.isPlaying = !this.isPlaying
}
}
}
</script>
进度条与时间显示 监听 audio 的 timeupdate 事件更新进度:

// 在 mounted 中添加事件监听
mounted() {
this.$refs.audioPlayer.addEventListener('timeupdate', () => {
this.currentTime = this.$refs.audioPlayer.currentTime
this.duration = this.$refs.audioPlayer.duration
})
}
进阶功能实现
播放列表管理 使用数组存储歌曲列表并实现切换逻辑:
data() {
return {
playlist: [
{ id: 1, title: '歌曲1', url: 'song1.mp3' },
{ id: 2, title: '歌曲2', url: 'song2.mp3' }
],
currentIndex: 0
}
},
computed: {
currentSong() {
return this.playlist[this.currentIndex]
}
}
音量控制 添加音量滑块并绑定到 audio 元素:

<input type="range" min="0" max="1" step="0.01" v-model="volume">
watch: {
volume(newVal) {
this.$refs.audioPlayer.volume = newVal
}
}
性能优化建议
- 使用 Web Audio API 替代
<audio>标签实现更复杂的音频处理 - 对移动端添加触摸事件支持
- 实现音频预加载减少等待时间
- 添加播放模式切换(单曲循环/列表循环/随机播放)
常见问题解决方案
跨浏览器兼容性
- 提供多种音频格式源:
<audio ref="audioPlayer"> <source src="song.mp3" type="audio/mpeg"> <source src="song.ogg" type="audio/ogg"> </audio>
移动端自动播放限制 需要用户交互事件触发后才能播放,可添加引导提示
状态持久化 使用 vuex 或 localStorage 保存播放进度和播放列表






