gpt4 book ai didi

Javascript 和 Howler.js - 如何选择随机声音?

转载 作者:行者123 更新时间:2023-11-29 17:17:14 25 4
gpt4 key购买 nike

我对 javascript 比较陌生,并尝试在 mousemove 上播放随机选择的声音。我无法上类,希望得到帮助。我正在使用 howler.min.js 来控制声音,因此在播放下一个声音之前不会等待声音播放结束。这是代码:

  var soundObjects = [];
var lastSoundTime = Date.now();

c.addEventListener("mousemove",function(evt){



var mx = evt.clientX - this.offsetLeft;
var my = evt.clientY - this.offsetTop;
//console.log("clicked at x:" + mx + ", y:" + my);
//
circles.push(makeMovingCircle(mx, my));

var now = Date.now();
var elapsed = now - lastSoundTime;
console.log(elapsed);
if (elapsed < 250) {
return
}

lastSoundTime = now;

new Howl({

var sounds = ['splash.mp3',
'splash.ogg',
'splash1.mp3',
'splash1.ogg',
'splash2.mp3',
'splash2.ogg',
'splash3.mp3',
'splash3.ogg',
'splash4.mp3',
'splash4.ogg',
'splash5.mp3',
'splash5.ogg'];

var soundFile = sounds[Math.floor(Math.random()*sounds.length)];
}
}).play();

最佳答案

这里最大的问题是您试图在 Howl 对象中定义变量,这是您做不到的。第二个问题是您只选择了所需的声音文件之一。我还建议您预加载所有可能的声音文件,然后随机播放一个,而不是每次都创建一个新的 Howl 对象。试试这个:

var soundObjects = [];
var lastSoundTime = Date.now();

// Preload Howl objects
var sounds = ['splash', 'splash1', 'splash2', 'splash3', 'splash4', 'splash5'];
var howls = {};
for (var i=0; i<sounds.length; i++) {
howls[sounds[i]] = new Howl({
urls: [sounds[i] + '.mp3', sounds[i] + '.ogg']
});
}

c.addEventListener('mousemove', function(evt){

var mx = evt.clientX - this.offsetLeft;
var my = evt.clientY - this.offsetTop;
circles.push(makeMovingCircle(mx, my));

var now = Date.now();
var elapsed = now - lastSoundTime;
console.log(elapsed);
if (elapsed < 250) {
return;
}

lastSoundTime = now;

// Select a random sound and play it
var sounds = ['splash', 'splash1', 'splash2', 'splash3', 'splash4', 'splash5'];
var soundFile = sounds[Math.floor(Math.random() * sounds.length)];

howls[soundFile].play();

}, false);

关于Javascript 和 Howler.js - 如何选择随机声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16403203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com