javascript - 每次在javascript循环上随机数

标签 javascript audio random

我试图使用howler.js播放随机音频文件,然后超时选择一个不同的随机文件,使其循环播放。我在播放和循环播放,但每次循环都使用相同的文件。唯一的随机选择是在初始负载上。

这就是我所拥有的:

    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()

这会愉快地播放音频文件夹中3个随机wav文件之一,但仅在加载时随机选择。然后,同一文件将无限循环。

对javascript来说还很陌生,因此不胜感激。谢谢。

最佳答案

这个怎么样?

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

更新

回答下面的评论,这是在继续播放下一个随机声音之前重复播放每种声音四次的一种方法:
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();

关于javascript - 每次在javascript循环上随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359189/

相关文章:

javascript - 克隆年份和月份中的 jquery 日期选择器不起作用,默认日期未显示

音频合成最佳实践

iphone - 在 Objective-C 中随机化 NSArray 的规范方法

java - 生成一系列值之间的随机 double - Java

Javascript 类作为对象的子对象

javascript - 了解 AngularJS 指令方法绑定(bind)是否默认为 angular.noop

javascript - CSS 过渡时间未应用于变换

java - 在 java 中寻找用于音频控件的开源 gui 组件

iphone - AudioUnit 输入样本

c# - 如何以 "natural"方式高效地在 2D 表面上展开对象?