I'm using HTML5 to program games;
(我正在使用HTML5来编写游戏;)
the obstacle I've run into now is how to play sound effects.(我现在遇到的障碍是如何播放声音效果。)
The specific requirements are few in number:
(具体要求很少:)
My first approach was to use the HTML5 <audio>
element and define all sound effects in my page.
(我的第一种方法是使用HTML5 <audio>
元素并在我的页面中定义所有声音效果。)
Firefox plays the WAV files just peachy, but calling #play
multiple times doesn't really play the sample multiple times.(Firefox只播放WAV文件,但多次调用#play
并不能真正多次播放样本。)
From my understanding of the HTML5 spec, the <audio>
element also tracks playback state, so that explains why.(根据我对HTML5规范的理解, <audio>
元素还可以跟踪播放状态,因此可以解释原因。)
My immediate thought was to clone the audio elements, so I created the following tiny JavaScript library to do that for me (depends on jQuery):
(我的直接想法是克隆音频元素,所以我创建了以下微小的JavaScript库来为我做(取决于jQuery):)
var Snd = {
init: function() {
$("audio").each(function() {
var src = this.getAttribute('src');
if (src.substring(0, 4) !== "snd/") { return; }
// Cut out the basename (strip directory and extension)
var name = src.substring(4, src.length - 4);
// Create the helper function, which clones the audio object and plays it
var Constructor = function() {};
Constructor.prototype = this;
Snd[name] = function() {
var clone = new Constructor();
clone.play();
// Return the cloned element, so the caller can interrupt the sound effect
return clone;
};
});
}
};
So now I can do Snd.boom();
(所以现在我可以做Snd.boom();
)
from the Firebug console and play snd/boom.wav
, but I still can't play the same sample multiple times.(从Firebug控制台播放snd/boom.wav
,但我仍然无法多次播放相同的样本。)
It seems that the <audio>
element is really more of a streaming feature rather than something to play sound effects with.(似乎<audio>
元素实际上更像是流媒体功能,而不是播放音效的东西。)
Is there a clever way to make this happen that I'm missing, preferably using only HTML5 and JavaScript?
(是否有一种聪明的方法可以实现这一点,我很想忘记,最好只使用HTML5和JavaScript?)
I should also mention that, my test environment is Firefox 3.5 on Ubuntu 9.10.
(我还要提一下,我的测试环境是Ubuntu 9.10上的Firefox 3.5。)
The other browsers I've tried - Opera, Midori, Chromium, Epiphany - produced varying results.(我尝试过的其他浏览器--Opera,Midori,Chromium,Epiphany--产生了不同的结果。)
Some don't play anything, and some throw exceptions.(有些人不玩任何东西,有些人抛出异常。)
ask by Stéphan Kochen translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…