audio auto play next song when previous is finished

rockarou picture rockarou · Sep 5, 2016 · Viewed 12.6k times · Source

I want to create an audio background player where user can only click on image to play or stop the playback. I have trouble creating or rewirting existing codes to make a playlist for it, that automatically plays next song when previous is finished. I want to do it in vanilla js.
Here is what I have so far:
https://jsfiddle.net/rockarou/ad8Lkkrj/

var imageTracker = 'playImage';

swapImage = function() {
  var image = document.getElementById('swapImage');
  if (imageTracker == 'playImage') {
    image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_pause_01.png';
    imageTracker = 'stopImage';
  } else {
    image.src = 'http://findicons.com/files/icons/129/soft_scraps/256/button_play_01.png';
    imageTracker = 'playImage';
  }
};

var musicTracker = 'noMusic';

audioStatus = function() {
  var music = document.getElementById('natureSounds');
  if (musicTracker == 'noMusic') {
    music.play();
    musicTracker = 'playMusic';
  } else {
    music.pause();
    musicTracker = 'noMusic';
  }
};

Answer

SilentTremor picture SilentTremor · Sep 5, 2016

here is the trick to trigger next song:

music.addEventListener('ended',function(){
      //play next song
    });

How to play another song on same audio tag:

 music.pause();
 music.src = "new url";
 music.load();
 music.play();

Now here is a cool example of a playlist in html5, you can load each song at the time, case some clients (mobile) will not be happy when you consume the traffic, in next example all audios are loaded at same time to have a smooth transition from song to song, loading the songs:

//playing flag 
var musicTracker = 'noMusic';
//playlist audios
var audios = [];
 $(".song").each(function(){
        var load = new  Audio($(this).attr("url"));
    load.load();
    load.addEventListener('ended',function(){
       forward();
    });
    audios.push(load);
 });
//active track
var activeTrack = 0;

Highlighting witch song is playing, with a bit of jquery, yeah, case yeah I'm lazy, lazy:

var showPlaying = function()
{
    var src = audios[activeTrack].src;
   $(".song").removeClass("playing");
   $("div[url='" + src + "']").addClass("playing");
};

Fiddle here

Note: If the sound's doesn't play, manually check if audio url's are accessible