HTML Audio - How to go to the next song automatically in a playlist with jQuery

1

I'm creating a playlist with HTML5 and jQuery. My markup:

<ol class="playlist">
  <li>
    audio 1
    <audio class="track" preload="none">
      <source src="<?php echo $siteroot; ?>/audio/joao/docevapor/audio1.ogg" type="audio/ogg">
    </audio>
  </li>
  <li>
    audio 2
    <audio class="track" preload="none">
      <source src="<?php echo $siteroot; ?>/audio/joao/docevapor/audio2.ogg" type="audio/ogg">
    </audio>
  <li>
    audio 3
    <audio class="track" preload="none">
      <source src="<?php echo $siteroot; ?>/audio/joao/docevapor/audio3.ogg" type="audio/ogg">
    </audio>
  </li>
</ol>

And my script:

$(function() {

  if($('.playlist')) {

    $('.playlist').find('li').prepend('<button class="control play">&#9654;</button>');

    $('.playlist li').on('click', '.play', function() {

      var index = $(this).parent().index();

      var track = $(this).parent().find('.track').eq(0);

      $('.playlist .track').trigger('pause');
      $('.playlist .play').removeClass('active');

      $(this).addClass('active');
      track.trigger('load').trigger('play');

    });
  }
});

I need that when a song in the playlist finishes its execution the next song in the playlist will play, until the last one. How to do this?

    
asked by anonymous 29.05.2015 / 17:56

2 answers

1

You have to detect the event ended and then start the next song.

$('#myAudio').on('ended', function() {
   // correr código aqui
});

In your specific code you can do this (not tested):

var atual = 0,
    next = 0;

function tocador(playlist, tracks) {
    $('.playlist .track').trigger('pause');
    $('.playlist .play').removeClass('active');
    tocando = true;
    $(playlist).addClass('active');
    tracks.on('ended', function () {
        next = atual == tracks.length ? 0 : atual + 1;
        tracks.eq(next).trigger('load').trigger('play');
    });
    tracks.eq(atual).trigger('load').trigger('play');
}
$('.playlist').on('click', '.play', function (e) {
    atual = 0;
    var tracks = $(this).closest('ol').find('.track');
    tocador(this, tracks);
});

$('.playlist audio').on('play', function () {
    var index = $(this).closest('li').index() - 1;
    if (atual == index || next == index) return;
    atual = next = index;
    var tracks = $(this).closest('ol').find('.track');
    var playlist = $(this).closest('playlist').find('.play');
    tocador(playlist, tracks);
});

Example: link

    
29.05.2015 / 18:11
0

You add an eventListener to the "ended" of the current song and then start the next song.

You have a good working example here:

link

    
29.05.2015 / 18:22