“我想要它,所以当按下鼠标时,它会从代码顶部预加载的三个声音文件中随机播放一个声音文件。目前我一次只能播放一个声音文件”
function preload() {
bird = loadSound('kooka.mp3');
bird2 = loadSound('galah.mp3');
bird3 = loadSound('cuckoo.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
background(0);
}
function draw() {
kooka();
}
function kooka () {
if (mouseIsPressed) {
bird2.playMode('untildone');
bird2.play();
bird2.setVolume(0.3);
最佳答案
创建一个声音数组并从数组中“选择”一个随机声音:
let sounds = [bird, bird2, bird3];
let randomSound = sounds[Math.floor(Math.random()*sounds.length)];
Math.random()
生成一个介于 0.0 和 1.0 之间的随机数。所以 Math.random()*sounds.length
是一个 float >= 0.0 和 <sounds.length
。 Math.floor
获取小于或等于数字的整数值。
如果多次按下鼠标按钮,将播放多个声音。
为确保一次只播放一个声音,您必须在变量 (currentSound
) 中记下当前声音并验证声音是否已播放完毕,然后才能开始播放新声音。
此外使用 mousePressed()
回调而不是内置状态变量 mouseIsPressed
.该事件仅在按下鼠标时发生一次,而只要按下鼠标就会声明变量。例如:
function draw() {
}
let currentSound;
function mousePressed() {
let is_playing = currentSound && currentSound.isPlaying();
if (!is_playing) {
let sounds = [bird, bird2, bird3];
currentSound = sounds[Math.floor(Math.random()*sounds.length)];
currentSound.playMode('untilDone');
currentSound.play();
currentSound.setVolume(0.3);
}
}
关于javascript - 单击鼠标从预加载播放随机声音文件(mp3 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569754/