dee dee - 2 months ago 19
Javascript Question

Random number each time on javascript loop

Im trying to play a random audio file using howler.js and then reselect a different random file overtime it loops. I have it playing and looping but with the same file every time it loops. The only random selection is on initial load.

This is what I have:

var number = Math.floor((Math.random() * 3) + 1);
var sound1 = new Howl({
src: ['audio/'+number+'.wav'],
autoplay: false,
loop: false,
volume: 1.0,
onend: function() {
sound1.play()
}
});

sound1.play()


This happily plays one of 3 random wav files from audio folder but only selects randomly on load. The same file then loops infinitely.

Pretty new to javascript so any help appreciated. Thanks.

Answer

How about this?

var sounds = [];

function playRandom() {
  // play a random member of sounds
  sounds[Math.floor(Math.random() * sounds.length) + 1].play();
}

// load all the sounds ahead of time    
var numberOfSounds = 3;
for (var i = 0; i < numberOfSounds; i++) {
  sounds.push(new Howl({
    src: ['audio/' + i + '.wav'],
    autoplay: false,
    loop: false,
    volume: 1.0,
    onend: function () {
      // when one sound ends, play a new random one
      playRandom();
    },
  }));
}

// kick things off with the first random sound    
playRandom();

UPDATE

Answering the comment below, here's one way to play each sound four times repeatedly before moving on to the next random sound:

var sounds = [];

function playRepeatedly(sound, howManyTimes, callback) {
  // this is similar to using `onend` when you create the sound
  sound.once('end', function () {
    // if there are more repetitions to go
    if (howManyTimes > 1) {
      // play one less time
      playRepeatedly(sound, howManyTimes - 1, callback);
    } else {
      // if we're all done, call the callback
      callback();
    }
  });

  sound.play();
}

function playRandom() {
  // pick a random sound
  var sound = sounds[Math.floor(Math.random() * sounds.length) + 1];

  // play it 4 times and then play a new random sound
  playRepeatedly(sound, 4, function () {
    // this is the callback, which just plays a new random sound
    playRandom();
  });
}

// load all the sounds ahead of time    
var numberOfSounds = 3;
for (var i = 0; i < numberOfSounds; i++) {
  sounds.push(new Howl({
    src: ['audio/' + i + '.wav'],
    autoplay: false,
    loop: false,
    volume: 1.0, // no more `onend` here
  }));
}

// kick things off with the first random sound    
playRandom();
Comments