【问题标题】:In HTML5, can I play the same sound more than once at the same time?在 HTML5 中,我可以同时多次播放相同的声音吗?
【发布时间】: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;
}

【问题讨论】:

  • 你用什么播放音频?我假设它是&lt;audio&gt; 标签。
  • sound = new Audio("souce.wav"); sound.play();

标签: javascript html audio html5-audio


【解决方案1】:

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

var sound = document.getElementById("incomingMessageSound")
var sound2 = sound.cloneNode()
sound.play()
sound2.play()

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

【讨论】:

  • 由于我创建了一个带有源标签的音频标签作为子标签 (&lt;audio&gt;&lt;source src="sound.mp3"/&gt;&lt;/audio&gt;),我需要将可选的 deep 参数设置为 true (sound.cloneNode(true)) 以便play 方法在克隆节点上工作。
【解决方案2】:

多次加载声音以模拟复音。以循环方式播放它们。在matthewtoledo.com 上查看我的演示。具体来说,函数_initSoundBank()

【讨论】:

  • 是的。这是我找到的最好方法。如果有人有更好的解决方案,我真的很想知道。
  • 派对迟到了,但您也可以通过不播放原版来“伪造”您的循环赛:预加载您的剪辑,然后改用audio.cloneNode(true).play(),这样您就总是 播放新副本。
【解决方案3】:

是的,单个&lt;audio&gt; 对象一次只能播放一首曲目。考虑&lt;audio&gt; 对象有一个currentTime 属性来指示音轨的当前位置:如果&lt;audio&gt; 对象可以一次播放多个音轨,那么currentTime 会反映什么值?

Is playing sound in Javascript performance heavy? 上查看我的解决方案以获取此问题的超集。 (基本上,添加相同声音的重复&lt;audio&gt;标签。)

【讨论】:

  • 啊哈!我知道有人在我的脑海中植入了这个想法......谢谢;)
【解决方案4】:

虽然目前仅在 FireFox 和 Chrome 中实现,但将来您应该使用专为浏览器中的游戏和音频应用程序设计的 WebAudio API

在那里,您可以多次播放任何声音并用它做一些其他有趣的事情。

一个很好的教程在这里:http://www.html5rocks.com/en/tutorials/webaudio/games/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多