Vue:点击播放音频,再次点击暂停多个曲目
Vue: click to play audio, click again to pause for multiple tracks
我有 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()
}
},
我有 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()
}
},