【发布时间】:2012-05-10 06:38:01
【问题描述】:
我正在制作一个经常播放声音的游戏。我注意到声音在播放时不会再次播放。例如,玩家与墙壁发生碰撞,播放“砰”的一声。但是,如果玩家撞到一面墙,然后又快速撞到另一面墙,只会播放“砰”的一声,我相信这是因为第一个声音没有完成。真的吗?我应该如何避免这种情况?我想过预加载声音 3 次,总是播放那个声音的不同副本,但这似乎很愚蠢......
已解决:
事实证明我是对的...您需要预加载多个版本的声音,然后循环播放它们。
代码:
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;
}
【问题讨论】:
-
你用什么播放音频?我假设它是
<audio>标签。 -
sound = new Audio("souce.wav"); sound.play();
标签: javascript html audio html5-audio