VizuaaLOG
VizuaaLOG

Reputation: 53

HTML5 Audio Tag Changing Src when finished. jQuery

I have created a audio element with a ul. In the ul is list items which are linked to different songs. I have gotten the song to change when the item is clicked and it all works however i would like the song to also change when the current playing song finishes. Below is my html and js.

HTML:

<div id="mp3_player">
    <div id="audio_box">
        <audio id="audioPlayer" preload="auto" src="" controls="controls"></audio>
    </div>
</div>

<ul id="songSelector">
    <a href="song1.mp3"><li>song1</li></a>
    <a href="song2.mp3"><li>song2</li></a>
    <a href="song3.mp3"><li>song3</li></a>
    <a href="song4.mp3"><li>song4</li></a>
</ul>

The source doesn't have a value becasuse it is added in another part of my script.

JS:

$(audio).bind('ended', function() {
    var testing = $('#songSelector').next().attr('href');
    alert(testing);
})

The alert returns undefined when the song finished when it should return the link on the next li element. I just cant figure out what i am doing wrong.

Thanks in advanced.

Upvotes: 2

Views: 1330

Answers (1)

kalley
kalley

Reputation: 18472

Right now, $('#songSelector').next() is going to whatever is after #songSelector in the dom. You probably need to keep track of which one is "current" in another variable.

var currentSong = $('#songSelector').find('a:first');
$(audio).bind('ended', function() {
    var next = currentSong.next();
    if ( next.length ) {
        currentSong = next;
    } else {
        /* uncomment this if you want it to loop back to the beginning */ 
        // currentSong = $('#songSelector').find('a:first');
    }
    var testing = currentSong.attr('href');
    alert(testing);
});

Then you just need to update currentSong in your click handler as well.

Upvotes: 1

Related Questions