Vue:点击播放音频,再次点击暂停多轨

时间:2021-05-02 20:50:29

标签: javascript html vue.js html5-audio

我有 100 个音轨,每个音轨都有一个唯一的 mp3 URL。当用户点击一个音轨时,它会播放,如果用户点击另一个音轨,当前音轨会停止并播放点击的音轨。但是,如果用户再次单击它,我无法弄清楚如何暂停当前曲目。请注意,如果用户单击当前播放曲目以外的任何其他曲目,我不想暂停音频。

这是我的代码

脚本:

      changeSong: function (index) {

        if (index !== undefined) {
          this.audio.pause();
          this.currentSong = index;

        }

        this.audioFile = this.musicPlaylist[this.currentSong].url;
        this.audio = new Audio(this.audioFile);

        if (this.audio.paused) { 
        this.audio.play()
} 

      },

模板:

<li class="item" v-for="(item,index) in musicPlaylist" :key="index"
                      v-bind:class="{  'active':isCurrentSong(index) }" v-on:click="changeSong(index)">

1 个答案:

答案 0 :(得分:2)

尝试这样的事情。这是伪代码,您可能需要稍微调整一下。

changeSong: function(index) {

  // a song is playing/paused and it's clicked again
  if (this.currentSong != null && this.currentSong === index) {
     // want to pass 0 through^ since it's legit index
    if (this.audio.paused) {
      return this.audio.play()
    } else {
      return this.audio.pause()
    };
    // ^ returns from from the function in case of play/pause existing song
  }

  // --- a new song is clicked ---

  // pause current song before losing reference to it.
  this.audio.pause()

  this.currentSong = index;
  this.audioFile = this.musicPlaylist[this.currentSong].url;
  this.audio = new Audio(this.audioFile);

  /* not sure if this is needed anymore.
   * Does audio start playing automatically? Remove if not needed
   */

  if (this.audio.paused) {
    this.audio.play()
  }
},