简体   繁体   中英

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.

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.

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.

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.

Check it out. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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