简体   繁体   中英

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

I'm trying to make a game which is based on a sampler. The aim of the game is to copy a sequence generated using random numbers. I have an array which has the randomly generated numbers and using .each() i'm trying to get each value to play a sample which is working but playing all the samples at the same time. I've got the samples to each play for one second each but what i need is one sample to be playing every second, sequentially.

Here is what i have so far:

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

Thank you

You can do something like this:

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

  });

Now in this case first song will play @ 1000*0 secs next @ 1000*1 next @ 1000*2 so on...

Hope this helps!

You can make it manually like this:

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

By this way you control everything, when to start the next audio by editing setTimeout(playNext, audio.duration * 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM