简体   繁体   中英

How to auto play next song with vanilla javascript

Hi I am trying to automatically play the next song when the current playing song is over.

I also wanted to know how I could make sure the playlist starts from the beginning when the last song ends.

Thank you !

 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>

Try this, Your are not using array in correct way

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM