Javascript and Howler.js - how to choose a random sound?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 19:18:40

Your biggest issue here is that you are trying to define variables inside the Howl object, which you can't do. The second problem is that you are only selecting one of the needed sound files. I would also suggest that you preload all the possible sound files and then play one at random rather than creating a new Howl object each time. Try this:

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!