在Chrome中播放多个声音

3

我正在为Facebook开发一个HTML5游戏。我有以下HTML代码:

<audio style="visibility: hidden;" controls="controls" id="sound-0">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>
<audio style="visibility: hidden;" controls="controls" id="sound-1">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>
<audio style="visibility: hidden;" controls="controls" id="sound-2">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>
<audio style="visibility: hidden;" controls="controls" id="sound-3">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>
<audio style="visibility: hidden;" controls="controls" id="sound-4">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>
<audio style="visibility: hidden;" controls="controls" id="sound-5">
    <source src="sound/sound_new.ogg" type="audio/ogg"/>
    <source src="sound/sound_new.mp3" type="audio/mp3"/>
</audio>

以下是开始播放声音的JavaScript代码:
if (this.hitFlag > 6) this.hitFlag = 1;
var soundElem = document.getElementById('sound-' + (this.soundFlag % 6) + '0' );
soundElem.play();

每次点击鼠标都会触发一个声音事件。问题出现在Chrome浏览器上,经过几十次点击后,声音会消失或者播放延迟很大(几秒钟)。但是在Firefox或Opera中播放没有问题。

1
Chrome已经修复了许多<audio>延迟错误,但您能否将其记录为问题(new.crbug.com)并附上测试用例。 - ebidel
1个回答

2

这肯定是一个 bug,但我认为它与实际元素有关,而不是声音播放部分。您可以通过预加载音频,在每次播放声音时实例化新的音频对象,然后最终在每个节拍时检查声音对象,以确定它们是否已经完成播放,从而清理内存,轻松解决此问题。

当然,预加载就像:

var _mySnd = new Audio('my/snd/file/is/here.mp3');

实例化就像:

var _sndCollection = [];
var n = _sndCollection.length;

_sndCollection[n] = new Audio();
_sndCollection[n].src = _mySnd.src;
_sndCollection[n].play();

清理检查将会是:

for (var i = 0; i < _sndCollection.length; i++)
{
    if (_sndCollection[i].currentTime >= _sndCollection[i].duration)
    {
        _sndCollection.splice(i, 1);
        i--;
    }
}

我在自己的HTML5游戏引擎中使用类似这样的东西,到目前为止它一直运作得非常完美。


谢谢@ceprovence,圣诞节之后我会试一下你的代码!祝你圣诞快乐! - Mihail Velikov
这个(或类似的)似乎可以工作,但它不会将你限制在一个文件类型中,比如在你的示例代码中的 .mp3 文件。<audio> 标签可以干净地支持多种文件类型,当我一年前处理声音时,我发现我需要 .mp3、.ogg 和 .wav 来覆盖所有浏览器。 - Dragonfly
跟进:使用您的系统时,我遇到了声音延迟的问题,就好像_mySnd的预加载没有扩展到_sndCollection [n]一样。 - Dragonfly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接