2013-10-29 63 views
0

我正在使用JavaScript创建自己的音乐播放器,并且正在处理下一首歌曲按钮。我已将它设置到歌曲添加到播放列表的位置,并将其相应的ID号存储到数组中。然后,我索引数组,查找歌曲的当前ID,然后当用户下一首时,它会转到数组中的下一首歌曲。如何在javascript中获取数组的下一个元素?

这里是我的代码:

$(document).ready(function(){ 
    $("#player").prop("volume",".5"); 
}); 

    var xmlhttp=new XMLHttpRequest(); 
    xmlhttp.open("GET","playlist.xml",false); 
    xmlhttp.send(); 
    xmlDoc=xmlhttp.responseXML; 
    var songlist = new Array(); 
    var currentSong; 

function song_play(song_id){ 
    var player = document.getElementById("player"); 
    player.setAttribute("src", "Music/"+song_id+".mp3"); 
    player.play(); 

    songlist.push(song_id); 
    alert(JSON.stringify(songlist)); 
    currentSong = song_id; 

      var new_id=song_id-1; 
      $("#marquee").empty(); 
      $("#marquee").append("<span style='color:red;'>Now Playing: </span>"+xmlDoc.getElementsByTagName("artist")[new_id].childNodes[0].nodeValue+"-"); 
      $("#marquee").append(xmlDoc.getElementsByTagName("track")[new_id].childNodes[0].nodeValue); 

}; 

function add_song(song_id,new_id){ 
    var artist = xmlDoc.getElementsByTagName("artist")[new_id].childNodes[0].nodeValue; 
    var track = xmlDoc.getElementsByTagName("track")[new_id].childNodes[0].nodeValue; 
    $("#song_list").append("<a id="+song_id+" href='javascript:void(0)' onclick='song_play(this.id);' class='song'>"+artist+"-"+track+"</a><br/>"); 
}; 

function nextSong(currentSong){ 
     var currentSongIndex = songlist.indexOf(currentSong); 
     var newSong = songlist[currentSongIndex + 1]; 
     song_play(newSong); 
}; 

,我遇到的是,一旦我打了一个按钮,它会停止播放音乐结合在一起的问题。

回答

0

newSong代表歌曲对象,而不是歌曲的ID,而您的song_play方法实际上是使用歌曲ID。将nextSong功能更改为:

function nextSong(currentSong){ 
    var currentSongIndex = songlist.indexOf(currentSong); 
    song_play(currentSongIndex + 1); 
}; 
+0

谢谢您的回复。我只是尝试了这一点,它会重放当前的歌曲,而不是转到阵列中的下一首歌曲。 – divpi

+0

我还应该补充说明,数组中的对象也是歌曲的ID。 – divpi

+0

好吧,现在你提到我所说的将不起作用,你将XML文件中的所有歌曲添加到你的数组? –

相关问题