Search code examples
javascripthtmlvue.jshtml5-audio

Vue: click to play audio, click again to pause for multiple tracks


I have 100 audio tracks, each with a unique mp3 URL. When a user clicks on an audio track it will play, if the user clicks on another track the current track stops and the clicked track plays. However, I am unable to figure out how to pause the current track if the user clicks it again. Note that I do NOT want to pause the audio if the user clicks on any other track other than the currently playing track.

Here is my code

Script:

      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()
} 

      },

Template:

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


Solution

  • Try something like this. It's pseudo code you might have to tweak it a bit.

    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()
      }
    },