使用“播放”按钮之前预加载 MP3 文件
我有以下代码:
function playSound(source) {
document.getElementById("sound_span").innerHTML =
"<embed src='" + source + "' hidden=true autostart=true loop=false>";
}
<span id="sound_span"></span>
<button onclick="playSound('file.mp3');"></button>
单击播放后,MP3 就会被下载,然后开始播放。但是,如果它有 1 MB 左右,则可能需要一段时间。我需要的是预加载(就像您可以对图像所做的那样)。因此,当页面加载时,mp3 将被流式传输,例如,如果 10 秒后,用户按下“播放”按钮,他不必等到 mp3 被首先下载,因为它已经被流式传输。
有什么想法吗?预先感谢您的任何提示!
I have the following code:
function playSound(source) {
document.getElementById("sound_span").innerHTML =
"<embed src='" + source + "' hidden=true autostart=true loop=false>";
}
<span id="sound_span"></span>
<button onclick="playSound('file.mp3');"></button>
Once you click play, the MP3 gets downloaded, than it starts to play. However, it can take a while if it has like 1 MB. What I need is a preloaded (just like you can do with the images). So when the page loads, the mp3 will be streamed and if, for instance, 10 seconds later, the user pressed the 'play' button, he won't have to wait until the mp3 gets downloaded first, as it is already streamed.
Any ideas? Thanks in advance for any tip!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于较新的浏览器,您可以使用
进行预加载。设置
autoplay = false
。对于不支持的旧版浏览器,您可以使用
。要预加载声音,请将音量设置为-10000
。这将在浏览器的缓存中获取声音。然后,要播放它,您可以继续使用
执行当前操作。或者,如果您想利用 HTML5 功能,可以在返回的
元素上调用
.play()
。您甚至可以向
添加一个播放方法:然后像这样使用它:
唯一需要注意的是 FireFox 不支持 mp3。您必须将文件转换为 ogg。
工作演示:http://jsfiddle.net/PMj89/1/
You can preload using
<audio />
for newer browsers. Setautoplay = false
. For older browsers that don't support<audio />
, you can use<bgsound />
. To preload a sound, set the volume to-10000
.That will get the sound in your browser's cache. Then to play it, you can keep doing what you are doing with
<embed />
. Or if you want to take advantage of HTML5 features, you can call.play()
on the returned<audio />
element. You could even add a play method to the<bgsound />
:Then use it like this:
The only caveat is FireFox doesn't support mp3. You'll have to convert your files to ogg.
Working demo: http://jsfiddle.net/PMj89/1/
您可以使用 HTML5
元素
preload
属性,并依靠。
You can use the HTML5
<audio>
element'spreload
attribute, and fall back on<embed>
.