使用Javascript和/或HTML5预加载声音

Preload a sound using Javascript and/or HTML5

本文关键字:加载 声音 HTML5 Javascript 使用      更新时间:2023-09-26

我正在创建一个Joomla!组件,我想在鼠标点击时播放特定的声音。

我有以下代码:

        var context = new AudioContext(); 
        var sound; 
        var playSound = context.createBufferSource();
        var getSound = new XMLHttpRequest();
        getSound.open("GET", "clapping.wav", true);
        getSound.responseType = "arraybuffer";
        getSound.onload = function() {
        context.decodeAudioData(getSound.response, function(buffer){
        sound = buffer;     
        });     
        }
        getSound.send();
        getSound.send();
        setTimeout(function(){  
        playSound.buffer = electro;
        playSound.connect(context.destination);         
        },3500); 
        jQuery("#bgchanger").click(function() {     
        playSound.start(0);     
        }

这工作得很好,但我面临的问题是,声音播放几秒钟后,当我点击按钮,而不是立即,所以我想要它直接播放

感觉有点傻,我刚刚注意到为什么会发生这种情况…他们几分钟前发给我的文件,我才注意到它有一个2.5秒的静音在开始…我可以在Chrome上的调试屏幕上看到,当我加载页面时,文件在52ms后下载。