HardCodeStuds
HardCodeStuds

Reputation: 539

Playlist with <audio> JavaScript

I'm creating a personal small website and I want to play some songs on it. What I've tried to do is the following:

<script type="text/javascript">

var i=1;
var nextSong= "";
var audioPlayer = document.getElementById('audio');
audioPlayer.onended = function(){
    i++
    nextSong = "Music/"+i+".mp3";
    audioPlayer.src = nextSong;
    audioPLayer.load();
    audioPlayer.play();
    if(i == 37) // this is the end of the songs.
    {
        i = 1;
    }
    
}
</script>
<audio id="audio"  src="Music/1.mp3"controls="controls" autoplay="autoplay"   align=""> </audio>

However, I can't get this to work. It just plays the first song and doesn't execute the JS. I've tried alerting the state of i for example but it doesn't do anything.

Upvotes: 3

Views: 14626

Answers (3)

Portal Bimmer Musik
Portal Bimmer Musik

Reputation: 1

var i=1; var nextSong= ""; function setup() { document.getElementById('audio').addEventListener('ended', function(){ i++; nextSong = "Music/"+i+".mp3"; audioPlayer = document.getElementById('audio'); audioPlayer.src = nextSong; audioPLayer.load(); audioPlayer.play(); if(i == 37) // this is the end of the songs. { i = 1; } }, false); }

Upvotes: -3

David Jashi
David Jashi

Reputation: 4511

Try this:

<script type="text/javascript">

var i=1;
var nextSong= "";
function setup() {
    document.getElementById('audio').addEventListener('ended', function(){
        i++;
        nextSong = "Music/"+i+".mp3";
        audioPlayer = document.getElementById('audio');
        audioPlayer.src = nextSong;
        audioPLayer.load();
        audioPlayer.play();
        if(i == 37) // this is the end of the songs.
        {
            i = 1;
        }
        }, false);
}
</script>
<body onLoad="setup();">
<audio id="audio"  src="Music/1.mp3"controls="controls" autoplay="autoplay"   align=""> </audio>
</body>

Upvotes: 5

IvanH
IvanH

Reputation: 11

Amendment needed on this answer. You need to also identify the audio player, otherwise this won't work...

<script type="text/javascript">

function setup() {
    var i=1;
    var nextSong= "";
    audioPlayer = document.getElementById('audio');
    document.getElementById('audio').addEventListener('ended', function(){
        i=i+1;
        nextSong = "m"+i+".mp3";
        audioPlayer.src = nextSong;
        audioPlayer.load();
        audioPlayer.play();     
        }, false);

}
</script>
<body onLoad="setup();">
<audio id="audio"  src="m1.mp3" controls="controls" autoplay="autoplay" align=""> </audio>
</body>

Upvotes: 1

Related Questions