javascript 如何强制 HTML5 音频元素缓冲整首歌曲?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4764015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:48:09  来源:igfitidea点击:

How can I force an HTML5 audio element to buffer an entire song?

javascripthtmlaudiohtml5-audio

提问by George

I'm developing a local server that will stream a user's audio files so they can access them via web browsers using the HTML5 audio object. Since these files are on the user's computer, I expect the files to be buffered completely when they are loaded, but for certain large files, the songs get buffered part of the way, then stop, and resume buffering some time later.

我正在开发一个本地服务器,它将流式传输用户的音频文件,以便他们可以使用 HTML5 音频对象通过 Web 浏览器访问它们。由于这些文件在用户的计算机上,我希望这些文件在加载时会被完全缓冲,但对于某些大文件,歌曲会在中途缓冲,然后停止,并在一段时间后恢复缓冲。

My question is: how can I force the audio object to buffer the entire song at once? Can I do this from javascript, do I have to set an attribute on the audio object, or is there anything else I can do?

我的问题是:如何强制音频对象一次缓冲整首歌曲?我可以从 javascript 中做到这一点,我是否必须在音频对象上设置一个属性,或者还有什么我可以做的吗?

回答by Ahi Tuna

The solution I found was this:

我找到的解决方案是这样的:

function load() {
    a.play();
    setTimeout("a.pause()", 10);
}

Play the file and pause it 10ms later, then the browser will buffer the entire song.

播放文件并在 10 毫秒后暂停,然后浏览器将缓冲整首歌曲。

回答by ayke

You can use the load()method. This basically forces preload="auto". But it probably won't buffer the whole thing.

您可以使用该load()方法。这基本上是强制的preload="auto"。但它可能不会缓冲整个事情。

I had the issue that audio wasn't preloaded on mobile devices (even with preload=auto), but this method worked.

我遇到的问题是移动设备上没有预加载音频(即使使用preload=auto),但这种方法有效。

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dfnReturnLink-2

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dfnReturnLink-2

Another option is to load the data via an XMLHttpRequest as a binary blob and set the <audio>element's srcattribute to the blob URI.

另一种选择是通过 XMLHttpRequest 作为二进制 blob 加载数据,并将<audio>元素的src属性设置为 blob URI。

(I personally don't really like the play/pause hack.)

(我个人不太喜欢播放/暂停技巧。)

回答by joeforker

You could set the preload="auto" attribute. It's not guaranteed to do anything, but it's supposed to tell the user agent to buffer as much as it wants without concern for the remote end. http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#attr-media-preload

您可以设置 preload="auto" 属性。它不能保证做任何事情,但它应该告诉用户代理尽可能多地缓冲而不用担心远程端。http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#attr-media-preload