在HTML5中,我可以同时播放多次相同的声音吗? [英] In HTML5, can I play the same sound more than once at the same time?
问题描述
我正在制作一个游戏,其中经常播放声音。我注意到声音在播放时不会再播放。例如,玩家与墙壁碰撞,发出砰砰声。但是,如果玩家与一面墙碰撞,然后迅速与另一面墙发生碰撞,则只会发出一声砰砰的声音,我相信这是因为第一声音没有完成。真的吗?我应该如何避免这种情况?我想过将声音预加载三次,总是播放不同的声音副本,但这看起来相当愚蠢...
I'm making a game, in which sounds are often played. I noticed that a sound wont play again while it is being played. For example, the player collides with a wall, a "thump" sound is played. But, if the player collides with one wall, and then quickly collides with another wall, only one "thump" sound is played, and I believe that this happens because the first sound didn't finish. Is that true? How should I avoid this? I thought of preloading the sound three times, always playing a different copy of that sound, but this seems rather stupid...
已解决:
原来我是对的...你需要预先加载多个版本的声音,然后循环播放它们。
Turns out I was right... You need to preload multiple versions of the sound and then circularly play them.
代码:
var ns = 3; //The number of sounds to preload. This depends on how often the sounds need to be played, but if too big it will probably cause lond loading times.
var sounds = []; //This will be a matrix of all the sounds
for (i = 0; i < ns; i ++) //We need to have ns different copies of each sound, hence:
sounds.push([]);
for (i = 0; i < soundSources.length; i ++)
for (j = 0; j < ns; j ++)
sounds[j].push(new Audio(sources[i])); //Assuming that you hold your sound sauces in a "sources" array, for example ["bla.wav", "smile.dog" "scream.wav"]
var playing = []; //This will be our play index, so we know which version has been played the last.
for (i = 0; i < soundSources.length; i ++)
playing[i] = 0;
playSound = function(id, vol) //id in the sounds[i] array., vol is a real number in the [0, 1] interval
{
if (vol <= 1 && vol >= 0)
sounds[playing[id]][id].volume = vol;
else
sounds[playing[id]][id].volume = 1;
sounds[playing[id]][id].play();
++ playing[id]; //Each time a sound is played, increment this so the next time that sound needs to be played, we play a different version of it,
if (playing[id] >= ns)
playing[id] = 0;
}
推荐答案
多次加载声音模拟复音。以循环方式播放它们。在 matthewtoledo.com 查看我的演示。具体来说,函数_initSoundBank()
Load the sound several times to simulate polyphony. Play them in round-robin fashion. Check out my demo at matthewtoledo.com. Specifically, the function _initSoundBank()
这篇关于在HTML5中,我可以同时播放多次相同的声音吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!