首页 > 解决方案 > 如何在使用 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>

标签: javascripthtmlloopsaudioplayback

解决方案


Firstable 不写内联 JavaScript,它有很多缺点,而且由于您想在当前结束时更改歌曲,所以您应该摆脱该loop属性,因为您不想只播放一首歌曲,并且您不需要跟踪音频元素的播放状态,它已经有一个属性audio.paused来判断它是否正在播放,我认为没有理由<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();
}
<audio id="myAudio" src="" preload="auto"></audio>
<button id="play-pause">PLAY/PAUSE SOUND</button>


推荐阅读