- Create a new object in
Vue
a component's method like so:data()
Audio
data() {
return {
audio: new Audio(require('@/assets/audio.mp3'))
}
}
It is assumed here that the audio file is located in the directory Vue
of the project src/assets
and named audio.mp3
.
- Add the following methods to
Vue
the component'smethods()
methods to control the playing and stopping of the audio:
methods: {
playAudio() {
// 开始播放音频
this.audio.play()
// 设置音频循环播放
this.audio.loop = true
},
stopAudio() {
if (
this.audio.currentTime > 0 &&
!this.audio.paused &&
!this.audio.ended &&
this.audio.readyState > 2
) {
// 停止播放音频
this.audio.pause();
} else {
// 重置音频时间轴
this.audio.currentTime = 0;
this.audio.pause();
}
}
}
- Add a button to
HTML
the template that triggers the audio to play and stop:
<template>
<div>
<button @click="playAudio">Play</button>
<button @click="stopAudio">Stop</button>
</div>
</template>
After completing the above steps, when the user clicks Play
the button, the audio will start playing in a loop. When the user clicks Stop
the button, the audio stops playing and starts over from the beginning.