如何解决使用JS结束第一首曲目后,如何自动播放另一首曲目?
我试图弄清楚如何在第一首曲目自动结束后立即播放另一首曲目,然后整个循环再次循环播放直到用户按下暂停。
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<audio id="myAudio" src="/sound/track.mp3" preload="auto" loop="true">
</audio>
<button id="play-pause"><a onClick="togglePlay()">PLAY/PAUSE SOUND</a></button>
解决方法
首先不要编写内联JavaScript,它有很多缺点,并且由于您想在当前结尾时更改歌曲,因此您应该摆脱loop
属性,因为您不想继续播放一首歌曲,您就不必跟踪音频元素的播放状态,它已经具有属性audio.paused
来判断它是否在播放,而且我认为没有理由添加{{ 1}}标签位于button元素内,这是一个播放列表的示例,这些列表都是动态的,可以随意添加所需的歌曲数量
<a>
var myAudio = document.getElementById("myAudio"),// a simple playing list
playingList = ["v1601656608/lambada_saxo_bxdmys","v1601656600/coffin_dance_saxo_ze81hy","v1601656611/mr_saxobeat_saxo_snh2di"],currentSong = 0;
// set the initial song url to be the first song in the playlist
myAudio.src = `https://res.cloudinary.com/dzcscgx8y/video/upload/${playingList[0]}.mp3`;
document.querySelector("#play-pause").onclick = function() {
myAudio.paused ? myAudio.play() : myAudio.pause();
}
myAudio.onended = function() {
// change the src to be the url of the next song,if the song is the last one in the playlist then the next should be the first one
this.src = `https://res.cloudinary.com/dzcscgx8y/video/upload/${playingList[++currentSong === playingList.length ? 0 : currentSong]}.mp3`;
// the audio player stops after playing each song,so after changing the src just launch the player
this.play();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。