2

我对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();
4

1 回答 1

5

您最大的问题是您试图在 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);
于 2013-05-06T18:18:18.513 回答