Reputation: 23
I want to auto to play next song after ended until last song. currently this my code.
HTML
<audio id="audio" src="Music/Inuyasha - Dearest ~Instrumental~.mp3" controls></audio>
<div class="btn" name="Music/Inuyasha - Dearest ~Instrumental~.mp3"></div><br>
<div class="btn" name="Music/Fear and Loathing in Las Vegas - Just Awake.mp3"></div><br>
<div class="btn" name="Music/Fear and Loathing in Las Vegas - How Old You Are Never Forget Your Dream.mp3"></div><br>
<div class="btn" name="Music/Fear and Loathing in Las Vegas - Short but Seems Long time of our Life Lyrics.mp3"></div><br>
<div class="btn" name="Music/My First Story - Calling You.mp3"></div><br>
<div class="btn" name="Music/My First Story - Bullet Radio.mp3"></div>
JavaScript
$() is document.getElementById(). i make it owns.
// my codes is not JQuery but Pure JavaScript.
var btn = document.getElementsByClassName('btn');
for(i=0; i < btn.length; i++){
btn[i].addEventListener('click', function(v){
$('audio').src = v.target.getAttribute('name');
$('audio').play();
}, false);
//Above codes is not problem but bottom for auto to change next song after ended
btn[i].index = i;
$('audio').addEventListener('ended', function(){
$('audio').src = btn[this.index+1].getAttribute('name');
$('audio').play();
}, false);
}
// my ended works is when song ended it will get current index array song then +1 the current index array and play it until last song. but it doesn't work.
Upvotes: 1
Views: 3819
Reputation: 436
var btn = document.getElementsByClassName('btn'),
currentBtn = -1;
for(i=0; i < btn.length; i++){
btn[i].addEventListener('click', function(){
// get current btn index
currentBtn = Array.prototype.slice.call( btn ).indexOf(this);
$('audio').btn[currentBtn].getAttribute('name');
$('audio').play();
}, false);
}
$('audio').addEventListener('ended', function() {
// get next button index. if it was last one - repeat from first btn
currentBtn++;
if (currentBtn >= btn.length) {
currentBtn = 0;
}
$('audio').src = btn[currentBtn].getAttribute('name');
$('audio').play();
}, false);
Upvotes: 1
Reputation: 62
I have found a way to do it in pure JS using an event listener. I hope you find the code helpful. Update: added support for adding more songs easily
<!DOCTYPE html>
<html>
<body>
<audio controls id="au" autoplay="autoplay">
<source src="Airport Lounge.mp3" type="audio/mpeg">
Your browser does not support this audio format.
</audio>
<script>
var c=0;
var songs = ["Airport Lounge.mp3", "Airport Lounge.mp3", "Airport Lounge.mp3"];
var a=document.getElementById("au");
a.addEventListener('ended', function(){
document.getElementById("au").src=songs[c];
a.load();
console.log(c);
c++;
if(c>=songs.length){
c=0;
}
});
</script>
</body>
</html>
Upvotes: 0