本文介绍了结束后自动切换到下一首歌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在结束直到最后一首歌后自动播放下一首歌。目前这是我的代码。
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
$()是document.getElementById()。我让它拥有。
$() 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);
}
//我的结束作品是当歌曲结束时它将获得当前索引阵列歌曲然后+1当前索引数组并播放它直到最后一首歌曲。但它不起作用。
// 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.
推荐答案
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);
这篇关于结束后自动切换到下一首歌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!