获取 timeOut() 以每秒从数组中播放一首歌曲

Getting timeOut() to play one song per second out of an array

本文关键字:播放 一首 timeOut 获取 数组      更新时间:2023-09-26

我正在尝试制作一个基于采样器的游戏。 游戏的目的是复制使用随机数生成的序列。我有一个数组,它有随机生成的数字,使用 .each() 我试图让每个值播放一个正在工作但同时播放所有样本的样本。我已经为每次播放提供了一秒钟的样本,但我需要的是每秒按顺序播放一个样本。

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

$('#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);
  });

谢谢

你可以做这样的事情:

$('#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依此类推...

希望这有帮助!

您可以像这样手动制作:

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);
    }
}

通过这种方式,您可以控制一切,何时通过编辑setTimeout(playNext, audio.duration * 1000);开始下一个音频