我想在结束直到最后一首歌后自动播放下一首歌。目前这是我的代码。
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
$()是document.getElementById()。我让它拥有。
// 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);
}
//我的结束作品是当歌曲结束时它将获得当前索引数组歌曲然后+1当前索引数组并播放它直到最后一首歌曲。但它不起作用。
答案 0 :(得分:0)
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);
答案 1 :(得分:0)
我已经找到了一种使用事件监听器在纯JS中完成它的方法。我希望你能找到有用的代码。更新:添加了对轻松添加更多歌曲的支持
<!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>