Search code examples
javascripthtmljqueryaudiojquery-selectors

JavaScript / JQuery Audio player "Next"


Here i got an audio player, I can double click the songs to play them but now i want to make the next button to work
I want the play button to play the next song, I dont know how to do it though, here is what I got so far

html:

<div class="audio-player-pad">
    <div class="container Test">
        <div id="audio-image">
            <img class="cover"/>
        </div>
    <div id="audio-player">
        <div id="audio-info">
            <span class="title"></span> - <span class="artist"></span> 
        </div>
         <input id="volume" type="range" min="0" max="10" value="5" />
         <br>
         <div id="buttons">
            <span>
                <button class="img" id="prev"></button>
                <button id="play"></button>
                <button id="pause"></button>
                <button id="stop"></button>
                <button id="next"></button>
            <div id="tracker">
                <div id="progressBar">
                    <span id="progress"></span>
                </div>
                <span id="duration"></span>
            </div>
            </span>
         </div>
             <table id="playlist">
                <tr class="bold clickN">
                    <td>ID:</td>
                    <td id="first" cover="emptycover.png" artist="Artist">Track-Name:</td>
                    <td>Artist:</td>
                    <td>Duration:</td>
                </tr>
                <tr>
                    <td class="idD" song="Weown.mp3" cover="ownCover.png" artist="The Wanted" >1</td>
                    <li><td >We Own The Night</td></li>
                    <td>The Wanted</td>
                    <td class="idD">3:25</td>
                </tr>
                <tr>
                    <td class="idD">2</td>
                    <li><td song="Live_For_The_Night_-_Krewella.mp3" cover="LiveCover.gif" artist="Krewella">Live For The Night</td></li>
                    <td>Krewella</td>
                    <td class="idD">3:27</td>
                </tr>
                <tr>
                    <td class="idD">3</td>
                    <li><td song="Not_Alone_Original_Mix.mp3" cover="NotCover.jpg" artist="Mako">Not Alone</td></li>
                    <td>Mako</td>
                    <td class="idD">4:46</td>
                </tr>
                <tr>
                    <td class="idD">3</td>
                    <li><td song="Two.mp3" cover="TwoCover.png" artist="Styline">Two Days Of Hope</td></li>
                    <td>Styline</td>
                    <td class="idD">3:55</td>
                </tr>
                <tr>
                    <td class="idD">4</td>
                    <li><td song="Volvo_IKEA_(Official lyric video).mp3" cover="ikeaCover.png" artist="Sander  Hoogendoorn">Volvo Ikea</td></li>
                    <td>Sander  Hoogendoorn</td>
                    <td class="idD">2:09</td>
                </tr>
                <tr>
                    <td class="idD">5</td>
                    <li><td song="TBD.mp3" cover="emptycover.png" artist="TBD">TBD</td></li>
                    <td>TBD</td>
                    <td class="idD">TBD</td>
                </tr>
                <tr>
                    <td class="idD">6</td>
                    <li><td song="TBD.mp3" cover="emptycover.png" artist="TBD">TBD</td></li>
                    <td>TBD</td>
                    <td class="idD">TBD</td>
                </tr>
            </table>
    </div>
</div>
</div>

JavaScript / JQuery:

var audio;

//Hide Pause Initially
$('#pause').hide();

//Initializer - Play First Song
initAudio($('#first'));

function initAudio(element){
    var song = element.attr('song');
    var title = element.text();
    var cover = element.attr('cover');
    var artist = element.attr('artist');

    //Create a New Audio Object
    audio = new Audio('Music/' + song);

    if(!audio.currentTime){
        $('#duration').html('0.00');
    }

    $('#audio-player .title').text(title);
    $('#audio-player .artist').text(artist);

    //Insert Cover Image
    $('img.cover').attr('src','Pics/Cover/' + cover);

    $('#playlist tr').removeClass('active');
    element.parent('tr').addClass('active');
}


//Play Button
$('#play').click(function(){
    audio.play();
    $('#play').hide();
    $('#pause').show();
    $('#duration').fadeIn(400);
    showDuration();
});

//Pause Button
$('#pause').click(function(){
    audio.pause();
    $('#pause').hide();
    $('#play').show();
});

//Stop Button
$('#stop').click(function(){
    audio.pause();      
    audio.currentTime = 0;
    $('#pause').hide();
    $('#play').show();
    $('#duration').fadeOut(400);
});

//Next Button
$('#next').click(function(){
    audio.pause();
    var next = $('#playlist tr.active').next();
    initAudio(next);
    audio.play();
    showDuration();
    $('#play').hide();
    $('#pause').show();

});

//Prev Button
$('#prev').click(function(){
    audio.pause();
    var prev = $('#playlist tr.active').prev();
    if (prev.length == 0) {
        prev = $('#playlist tr:last-child');
    }
    initAudio(prev);
    audio.play();
    showDuration();
    $('#play').hide();
    $('#pause').show();
});

//Playlist Song dblClick
$('#playlist td:nth-child(2)').dblclick(function () {
    audio.pause();
    initAudio($(this, 'td:nth-child(2)'));
    $('#play').hide();
    $('#pause').show();
    $('#duration').fadeIn(400);
    audio.play();
    showDuration();
});
//Playlist song click
$('#playlist td:nth-child(2)').click(function() {
    audio.pause();
    $('#pause').hide();
    $('#play').show(); 
});
//Volume Control
$('#volume').change(function(){
    audio.volume = parseFloat(this.value / 10);
});

//Time Duration
function showDuration(){
    $(audio).bind('timeupdate', function(){
        //Get hours and minutes
        var s = parseInt(audio.currentTime % 60);
        var m = parseInt((audio.currentTime / 60) % 60);
        //Add 0 if seconds less than 10
        if (s < 10) {
            s = '0' + s;
        }
        $('#duration').html(m + '.' + s);   
        var value = 0;
        if (audio.currentTime > 0) {
            value = Math.floor((100 / audio.duration) * audio.currentTime);
        }
        $('#progress').css('width',value+'%');
    });
}

Solution

  • There is no such thing as a "next/prev" default functionality in html5. All the api let you do is into a single track, and this is all.

    I'll create a little example of how you can handle this situation. Please, take in consideration that i'm kinda busy right now and it may have some typos. But i just want to show you the general logic to build a consistent music player.

    So, try using this modular/oo style and make your improves, i'm sure you can.

    You can use javascript to manage your tracks, like this:

    var getTrack = function( val ){
      var obj = TRACKS;
      var track = obj.filter(function( obj ) {
        return obj.id == val;
      });
      return track[0];
    }
    var playlist = [];
    var TRACKS = [{
        id: 0,
        name: 'music 1',
        src: 'path/to/file.mp3',
        icon: 'path/to/icon;jpg',
        foo: 'bar'
      },{
        id: 1,
        name: 'music 2',
        src: 'path/to/file.mp3',
        icon: 'path/to/icon;jpg',
        foo: 'bar'
      }];
    
    playlist = [1, 2];
    
    var player = function(){
      var currentPlaying = false;
      var playlistPos = false;
      var playlist = false;
      var trackList = false;
      this.setPlaylist = function( p ){
        playlist = p;
        playlistPos = 0;
        setTrack(trackList[0], 0);
        return this;
      }
      this.setTrackList = function( t ){
        trackList = t;
        return this;
      }
      this.setTrack = function( obj, i ){
        currentPlaying = obj;
        playlistPos = i;
        audio.src = obj.src;
        audio.load();
        //here you can manage the another
        //info data from the track object, like setting the track icon
        return this;
      }
      this.play = function( obj ){
        audio.play();
        return this;
      }
      this.stop = function(){
        audio.pause();
        audio.currentTime = 0;
        return this;
      }
      this.pause = function(){
        audio.pause();
      }
    
      //this is what you really want
    
      this.next = function(){
        if(playlist && currentPlaying){
          var next = (playlist[playlistPos++]) ? playlistPos++ : 0;
          setTrack(trackList[next], next);
        }
        return this;
      }
    }
    //Initialize
    PLAYER = new player();
    PLAYER.setTrackList(TRACK).setPlaylist(playlist).play();
    

    After that, you can simply do a

    PLAYER.next();
    //or even
    $('.next').on('click', PLAYER.next);
    

    And it will do the trick.