Search code examples
javascriptaudiohowler.js

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


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

Solution

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