来自数组Javascript的随机声音

时间:2013-05-22 04:46:17

标签: javascript jquery audio

按钮单击后,我尝试播放随机音效。基本上,我创建了一个声音数组,如下所示。我的目标是,当用户单击按钮时,我想从数组中选择一个随机声音,这仅在页面刷新后才有效。但是当用户在第二次或第三次点击按钮时,它将返回一次又一次返回相同的结果。

function sound_return(){
    var sound_array = ["sound1.mp3", "sound2.mp3"];
    var sound = sound_array[Math.floor(Math.random() * sound_array.length)];
        return sound;
    }

        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', 'sound/'+sound_return());
        audioElement.load()
        $.get();
        audioElement.addEventListener("load", function() {
        audioElement.play();
        }, true);

    $('#sound').click(function(event){
            event.preventDefault();
            audioElement.play();    
    });

1 个答案:

答案 0 :(得分:0)

您需要设置音频源并在每次点击期间加载

function sound_return(){
    var sound_array = ["sound1.mp3", "sound2.mp3"];
    var sound = sound_array[Math.floor(Math.random() * sound_array.length)];
    return sound;
}

var audioElement = document.createElement('audio');
audioElement.addEventListener("load", function() {
    audioElement.play();
    btn.hide();
}, true);
audioElement.addEventListener("ended", function() {
    btn.show();
}, true);


var btn = $('#sound').click(function(event){
    event.preventDefault();
    audioElement.setAttribute('src', 'sound/'+sound_return());
    audioElement.load();
});