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

岁酱吖の 提交于 2019-12-14 03:42:43

问题


I am rather new to javascript and trying to have random selected sounds playing on mousemove. I can't get to work and would appreciate help. I am using howler.min.js to control the sound so does not wait for the sound to play to end before it plays the next sound. Here is the code:

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

回答1:


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


来源:https://stackoverflow.com/questions/16403203/javascript-and-howler-js-how-to-choose-a-random-sound

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