Vue:点击播放音频,再次点击暂停播放多首曲目



我有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)">

试试这样的方法。这是伪代码,您可能需要对其进行一些调整。

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

最新更新