Vue automatically plays the audio prompt sound (according to the status value returned by the interface, the prompt sound. code==0: play the sound effect of success; else play the sound effect of failure)

Audio object

Foreword:

Sometimes we don't want to place an audio control on the page and click to play it manually, but use an icon click event or js to control its playback and pause operations. At this time, we need to use the Audio object , **The blogger here is a Vue project, so the same Audio instance used in data

Project requirements: input box input completed

1. Provide the prompt sound audio required by the project

insert image description here

2. Define an audio object in data and import the required audio

export default {
    
    
    data(){
    
    
        return {
    
    
            // 实例化一个音频播放器对象
            audio: new Audio()
            successUrl: require("../../../assets/music/success.mp3"),
            errorUrl: require("../../../assets/music/error.wav"),
        }
    }
}

3. In the method of calling the interface in the input box, call different sounds according to the return status of the interface

insert image description here

getInput() {
    
    
      this.queryParams = {
    
    
        code: this.barcode,
        name: this.pageOrderName,
      };
      operatePos(this.queryParams).then((res) => {
    
    
        this.name = "";
        this.barcode = "";
        if (res.code == 0) {
    
    
          // 开启自动播放
          this.audio.autoplay = true;
          this.audio.src = this.successUrl;
          this.sonList = res.data;
          this.getList(this.sonList);
          this.poData = this.sonList.lastScanBoxCode.slice(
            this.sonList.lastScanBoxCode.length - 1
          );
          this.resSize = this.sonList.platsize;
          this.$infoMsg.showInfoMsg(res.msg, this);
        } else {
    
    
          // 开启自动播放
          this.audio.autoplay = true;
          this.audio.src = this.errorUrl;
          this.$infoMsg.showErrorMsg(res.msg, this);
        }
      });
    },

Basic tips:

In the future, you only need to make it play by switching the src. According to different needs, you can set it to play automatically when the page is loaded, and then what to do after each audio is played, and the callback operation is performed through the end event.

created(){
    
    
    // 开启自动播放
    this.audio.autoplay = true;
    // 绑定播放完毕事件,每次放完了可以做一些收尾的事
    this.audio.addEventListener('ended', () => {
    
    
      // dosomething...
    });
}

Set the src mode of playback:

this.audio.src = url

How to play pause:

await this.audio.play() // 播放
this.audio.pause() // 暂停
// 因为加载音频文件是需要时间的,所以play方法返回的上一个promise,我们要等待他加载完成才能播放

After these basic understandings, you can control the playback of the sound by yourself~

Guess you like

Origin blog.csdn.net/Maxueyingying/article/details/127615736