Add audio in vue, and control playback to stop playback

  1. Create a new object in Vuea 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 Vueof the project src/assetsand named audio.mp3.

  1. Add the following methods to Vuethe component's methods()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();
     }
  }
}
  1. Add a button to HTMLthe 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 Playthe button, the audio will start playing in a loop. When the user clicks Stopthe button, the audio stops playing and starts over from the beginning.

Guess you like

Origin blog.csdn.net/weixin_43483746/article/details/130105349