简体   繁体   English

在移动浏览器上同时播放多个一键式音效?

[英]Playing multiple one shot sound effects at the same time on mobile browsers?

I'm trying to play a sound effect when the user clicks a button in my web app. 当用户单击Web应用程序中的按钮时,我正在尝试播放声音效果。

I first tried this method: 我首先尝试了这种方法:

var sound = new Audio("soundeffect.ogg");
function clickHandler(){
    sound.play();
}

However, if the user presses the button twice in quick succession, the sound is only played once. 但是,如果用户快速连续按两次按钮,则声音只会播放一次。 I assumed this is because the sound hasn't finished playing, and therefore isn't rewinded. 我认为这是因为声音尚未播放完毕,因此不会倒带。

I then tried this solution. 然后,我尝试了这种解决方案。

var sound = new Audio("soundeffect.ogg");
function clickHandler(){
    sound.currentTime = 0;
    sound.play();
}

However, this causes the first sound to cut off before the next one is played. 但是,这会导致第一个声音在播放下一个声音之前被切断。

I then tried this version, which creates a new sound effect each time the button is clicked: 然后,我尝试了此版本,每次单击该按钮时,都会创建一个新的声音效果:

function clickHandler(){
    var sound = new Audio("soundeffect.ogg");
    sound.play();
}

This works perfectly on my developer machine, but using android chrome on mobile data, the sound effect seems to have to load each time the button is clicked, causing a delay of several seconds before the sound is played. 这在我的开发人员机器上完美运行,但是在移动数据上使用android chrome时,每次单击按钮似乎都必须加载声音效果,这会导致播放声音之前延迟几秒钟。

I was hoping declaring the sound effect in the global scope, then cloning it might help keep it in the cache, but it didnt seem to help. 我希望在全局范围内声明声音效果,然后克隆它可能有助于将其保留在缓存中,但似乎没有帮助。

var sound = new Audio("soundeffect.ogg");
function clickHandler(){
    var oneShotSound = sound.cloneNode();
    oneShotSound.play();
}

I wrote a web audio library, Wad.js, which I think will help you in this case. 我写了一个Web音频库Wad.js,在这种情况下,我认为它将为您提供帮助。

var sound = new Wad({ source : 'soundeffect.ogg' });

sound.play();

Wad.js will create a new audio buffer source node every time you call play() , so you can hear multiple instances of the same sound, but all of those audio buffer source nodes use the same audio buffer, which saves you lots of computational work. 每次调用play() ,Wad.js都会创建一个新的音频缓冲区源节点,因此您可以听到相同声音的多个实例,但是所有这些音频缓冲区源节点都使用相同的音频缓冲区,从而节省了大量计算时间工作。

Check it out. 看看这个。 https://github.com/rserota/wad https://github.com/rserota/wad

However, cross-browser compatibility is not perfect. 但是,跨浏览器的兼容性并不完美。 I expect it'll work in chrome for android, but I haven't tested it. 我希望它可以在chrome for android中使用,但我尚未测试过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM