单击播放后,音频是否被阻止“自动播放”?

时间:2019-02-20 01:18:22

标签: html5 vue.js

我正在构建一个可以播放音乐的Vue应用。这是相关的HTML

<template>
  <div class="container">
      <button type="button" ref="play" class="btn btn-primary">
      <font-awesome-icon id="playIcon" icon="play" />
      </button>
      <audio ref="audio"></audio>
  </div>
</template>

这是播放音乐的方法。音频的来源已在较早的功能中正确设置。

togglePlay(update) {
      if (this.isLoaded != true) {
        return;
      }

      if (this.isPlaying == true) {
          this.audioDOM.pause();
          this.isPlaying = false;
          if (update) {
            this.sendUpdate();
          }
      } else {
          this.audioDOM.play();
          this.isPlaying = true;
          if (update) {
            this.sendUpdate();
          }
      }
    }

在Vue组件的mounted()部分中,我有这个:

this.playBtn.addEventListener("click", () => {
        this.togglePlay(true);
    }, false);

但是,它不会启动音频,因为到达第this.audioDOM.play()行时会引发自动播放错误,并说我需要提示用户输入。但是,很明显,用户是通过单击播放按钮来提供输入的!我需要更改什么?

2 个答案:

答案 0 :(得分:0)

您需要将事件传递给this.togglePlay。该事件必须存在于调用函数的上下文中,否则它将不知道它是由用户触发的。

尝试一下

<template>
  <div class="container">
      <button
          type="button"
          @click="togglePlay($event)" <!-- here I have added @click as an event handler -->
          class="btn btn-primary"
      >
      <font-awesome-icon id="playIcon" icon="play" />
      </button>
      <audio ref="audio"></audio>
  </div>
</template>
<script>
export default {
methods :{
    togglePlay(ev) { //since update is always true we don't need it,
      if (this.isLoaded != true) { // lets get the event instead
        return;
      }

      if (this.isPlaying == true) {
          this.audioDOM.pause();
          this.isPlaying = false;
          this.sendUpdate();
      } else {
          this.audioDOM.play();
          this.isPlaying = true;
          this.sendUpdate()
      }
    }

  }
}

<script>

答案 1 :(得分:0)

尴尬。原来错误是DOMException,因为我将源设置为错误。哎呀!

相关问题