vue3 实现音乐播放
时间: 2023-11-08 12:05:51 浏览: 49
要实现音乐播放,可以使用 HTML5 的 audio 标签,同时结合 Vue3 的响应式数据和生命周期函数来控制音乐的播放、暂停、进度等。
首先,在 Vue3 的 setup 函数中定义一个响应式数据,用于存储音乐的播放状态、当前播放时间和总时长:
```
import { ref } from 'vue'
export default {
setup() {
const audio = ref(null) // audio 元素
const isPlaying = ref(false) // 播放状态
const currentTime = ref(0) // 当前播放时间
const duration = ref(0) // 总时长
// 监听 audio 元素的事件
const onAudioPlay = () => {
isPlaying.value = true
}
const onAudioPause = () => {
isPlaying.value = false
}
const onAudioTimeUpdate = () => {
currentTime.value = audio.value.currentTime
duration.value = audio.value.duration
}
return {
audio,
isPlaying,
currentTime,
duration,
onAudioPlay,
onAudioPause,
onAudioTimeUpdate
}
}
}
```
然后,在模板中使用 audio 标签,并绑定相关事件和数据:
```
<template>
<div>
<audio ref="audio" @play="onAudioPlay" @pause="onAudioPause" @timeupdate="onAudioTimeUpdate">
<source src="music.mp3" type="audio/mpeg">
</audio>
<button @click="isPlaying ? audio.pause() : audio.play()">
{{ isPlaying ? '暂停' : '播放' }}
</button>
<div>
{{ currentTime }} / {{ duration }}
</div>
</div>
</template>
```
最后,在组件的 mounted 生命周期中获取 audio 元素,并调用 play 方法开始播放音乐:
```
import { ref, onMounted } from 'vue'
export default {
setup() {
const audio = ref(null)
// ...
onMounted(() => {
audio.value.play()
})
return {
audio,
// ...
}
}
}
```