如何使用香草javascript自动播放下一首歌曲

时间:2019-11-03 10:52:04

标签: javascript audio addeventlistener

嗨,我正在尝试在当前播放的歌曲结束时自动播放下一首歌曲。

我还想知道如何确保播放列表从最后一首歌曲结束时的开头开始。

谢谢!

var songs = [
  "song1.mp3",
  "song2.mp3",
  "song3.mp3",
  "song4.mp3"
];

var song = new Audio();
var currentSong = 0;
var len = currentSong.length - 1;

function playSong() {
  song.src = songs[currentSong];
  song.play();
}

// play the next song when current song ends
song.addEventListener("ended", function playNextS() {
      currentSong++;
      if (currentSong == len) {
        currentSong = 0;
        playSong();
      }
<div class="player">
  <div class="songCover"><img src="" alt="" /></div>
  <div class="about">
    <div class="songTitle"></div>
    <div class="Artist"></div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

尝试此操作,您未正确使用数组

var songs = [
  "song1.mp3",
  "song2.mp3",
  "song3.mp3",
  "song4.mp3"
];

var song = new Audio();
var currentSong = 0;
var len = songs.length;

function playSong(index) {
  song.src = songs[index];
  song.play();
}
song.addEventListener("ended", function playNextS() {
      currentSong++;
      if (currentSong == len) {
        currentSong = 0;
        playSong(currentSong);
      }
      else{
        playSong(currentSong);
      }
      
<div class="player">
  <div class="songCover"><img src="" alt="" /></div>
  <div class="about">
    <div class="songTitle"></div>
    <div class="Artist"></div>
  </div>
</div>