让timeOut()每秒播放一首歌曲

时间:2016-01-31 12:53:15

标签: javascript jquery

我试图制作一款基于采样器的游戏。游戏的目的是复制使用随机数生成的序列。我有一个数组,其中包含随机生成的数字并使用.each()我试图让每个值播放一个正在工作但同时播放所有样本的样本。我每次播放的样本都是1秒,但我需要的是每秒播放一个样本,顺序播放。

这是我到目前为止所拥有的:

$('#play').on("click", function(){
  startGame();
  message("Player 1 will start.  You have 3 lives remaining.  Input the correct sequence so you dont get booed off stage...Everyone is watching");
  $.each(generatedArray, function(index, value){
  var audio = new Audio("Sounds/" + value + ".wav");
  audio.play(audio.duration * 1000);
  });

谢谢

2 个答案:

答案 0 :(得分:2)

您可以这样做:

$('#play').on("click", function(){
  startGame();
  message("Player 1 will start.  You have 3 lives remaining.  Input the correct sequence so you dont get booed off stage...Everyone is watching");
  $.each(generatedArray, function(index, value){
  //here 1000 * index will run the song at the time interval
  window.setTimeout(function(){ 
     var audio = new Audio("Sounds/" + value + ".wav");
     audio.play(audio.duration * 1000);
  }, 1000*index);

  });

现在在这种情况下,第一首歌将播放@ 1000 * 0秒接下来@ 1000 * 1接下来@ 1000 * 2等......

希望这有帮助!

答案 1 :(得分:2)

你可以这样手动制作:

specific exception identified

通过这种方式,您可以通过编辑var crtIndex = 0; $('#play').on("click", function(){ startGame(); message("Player 1 will start. You have 3 lives remaining. Input the correct sequence so you dont get booed off stage...Everyone is watching"); playNext(); }); function playNext () { var audio = new Audio("Sounds/" + generatedArray[crtIndex] + ".wav"); audio.play(audio.duration * 1000); crtIndex++; if(crtIndex < generatedArray.length){ setTimeout(playNext, audio.duration * 1000); } }

来控制所有内容,何时开始下一个音频