在HTML5中,我可以同时播放多次相同的声音吗?

cor*_*zza 10 javascript audio html5 html5-audio

我正在制作一个经常播放声音的游戏.我注意到声音在播放时不再播放.例如,玩家与墙碰撞,播放"重击"声.但是,如果玩家与一面墙碰撞,然后迅速与另一面墙发生碰撞,则只会发出一声"砰砰"的声音,我相信这是因为第一声音没有完成.真的吗?我该怎样避免这个?我想过将声音预加载三次,总是播放不同的声音副本,但这看起来相当愚蠢......

解决了:

事实证明我是对的...你需要预先加载声音的多个版本,然后循环播放它们.

代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您可以克隆音频元素。我不知道您是否可以同时播放多个声音,但是这是您可以多次播放声音而不下载一次的方法。

var sound = document.getElementById("incomingMessageSound")
var sound2 = sound.cloneNode()
sound.play()
sound2.play()
Run Code Online (Sandbox Code Playgroud)

我知道这适用于chrome,这是我唯一需要的地方。祝好运!


mrb*_*000 2

多次加载声音以模拟复调音乐。以循环赛方式进行比赛。在matthewtoledo.com上查看我的演示。具体来说,函数_initSoundBank()

  • 迟到了,但你也可以通过不播放原始片段来“假装”你的循环:预加载你的剪辑,然后使用 `audio.cloneNode(true).play()` 代替,这样你_总是_获得新鲜的复制播放。 (2认同)