vue 实现音乐播放
Vue 实现音乐播放功能
基础播放器实现
使用HTML5的<audio>标签结合Vue的响应式特性实现基础播放功能。在模板中添加<audio>元素并绑定ref:
<template>
<audio ref="audioPlayer" :src="currentSong.url"></audio>
<button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
</template>
在Vue组件中控制播放状态:
export default {
data() {
return {
currentSong: {
url: 'https://example.com/song.mp3'
},
isPlaying: false
}
},
methods: {
togglePlay() {
const player = this.$refs.audioPlayer
this.isPlaying ? player.pause() : player.play()
this.isPlaying = !this.isPlaying
}
}
}
进度条与时间显示
添加进度条显示和控制功能,使用<input type="range">绑定音频当前时间:
<input
type="range"
v-model="currentTime"
:max="duration"
@input="seekTime"
>
<span>{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
在组件中添加相关逻辑:
data() {
return {
currentTime: 0,
duration: 0
}
},
mounted() {
const player = this.$refs.audioPlayer
player.addEventListener('timeupdate', () => {
this.currentTime = player.currentTime
})
player.addEventListener('loadedmetadata', () => {
this.duration = player.duration
})
},
methods: {
seekTime(e) {
this.$refs.audioPlayer.currentTime = e.target.value
},
formatTime(seconds) {
const mins = Math.floor(seconds / 60)
const secs = Math.floor(seconds % 60)
return `${mins}:${secs < 10 ? '0' : ''}${secs}`
}
}
音量控制
添加音量控制滑块:

<input
type="range"
v-model="volume"
min="0"
max="1"
step="0.01"
@input="setVolume"
>
组件中添加音量控制逻辑:
data() {
return {
volume: 0.7
}
},
mounted() {
this.$refs.audioPlayer.volume = this.volume
},
methods: {
setVolume() {
this.$refs.audioPlayer.volume = this.volume
}
}
播放列表功能
实现多歌曲切换功能,创建播放列表数组:
data() {
return {
playlist: [
{ id: 1, title: '歌曲1', url: 'url1.mp3' },
{ id: 2, title: '歌曲2', url: 'url2.mp3' }
],
currentIndex: 0
}
},
computed: {
currentSong() {
return this.playlist[this.currentIndex]
}
},
methods: {
playSong(index) {
this.currentIndex = index
this.$nextTick(() => {
this.$refs.audioPlayer.play()
this.isPlaying = true
})
}
}
高级功能扩展
添加音频可视化效果需要Web Audio API:

setupVisualizer() {
const audioCtx = new (window.AudioContext || window.webkitAudioContext)()
const analyser = audioCtx.createAnalyser()
const source = audioCtx.createMediaElementSource(this.$refs.audioPlayer)
source.connect(analyser)
analyser.connect(audioCtx.destination)
const bufferLength = analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
const draw = () => {
requestAnimationFrame(draw)
analyser.getByteFrequencyData(dataArray)
// 使用Canvas绘制可视化效果
}
draw()
}
第三方库集成
考虑使用现成的Vue音频播放器库如vue-aplayer:
npm install vue-aplayer
基础用法示例:
import VueAplayer from 'vue-aplayer'
export default {
components: {
VueAplayer
},
data() {
return {
song: {
title: '示例歌曲',
artist: '艺术家',
src: 'song.mp3',
pic: 'cover.jpg'
}
}
}
}
<vue-aplayer :music="song" autoplay/>
移动端适配
针对移动端浏览器需要特殊处理自动播放限制:
mounted() {
document.addEventListener('click', this.initAudio, { once: true })
},
methods: {
initAudio() {
// 用户交互后初始化音频
this.$refs.audioPlayer.load()
}
}






