使用HTML5音频标签流式传输MP3而不是下载它

3
document.ready函数中,我有以下代码:
audioElement = document.createElement('audio');

audioElement.setAttribute('src', 'http://www.mfiles.co.uk/mp3-downloads/Toccata-and-Fugue-Dm.mp3');

$('#ToggleStart').click(function () {
    audioElement.play();
});

$('#ToggleStop').click(function () {
    audioElement.pause();
});

问题在于当页面加载时,MP3文件被下载,由于这个MP3文件超过2MB,导致了显著的加载时间。我想要的是流式传输MP3文件。是否可能实现并且需要改变什么? 这里有jsFiddle
1个回答

9
你已经非常接近正确答案了。我看过了你的JSFiddle并且发现音频已经在流式传输了(我可以在文件下载完成之前播放它)。你可以通过检查浏览器中的网络流量轻松地看到这一点:

enter image description here

Chrome显示“部分内容”,但同时播放mp3。您的具体问题似乎是它下载和播放得太早了。因此,如果我们看一下spec,我们可以看到一些选项。
preload = "none" or "metadata" or "auto" or "" (empty string) or empty
Represents a hint to the UA about whether optimistic downloading of the audio stream itself or its metadata is considered worthwhile.
- "none": Hints to the UA that the user is not expected to need the audio stream, or that minimizing unnecessary traffic is desirable.
- "metadata": Hints to the UA that the user is not expected to need the audio stream, but that fetching its metadata (duration and so on) is desirable.
- "auto": Hints to the UA that optimistically downloading the entire audio stream is considered desirable.

由于您没有显示有关音频文件的任何信息,因此我们可以忽略元数据选项,这意味着您想设置preload =“none”属性。因此,如果您稍微更改JSFiddle以动态设置此属性:

audioElement.setAttribute('preload', "none");
audioElement.setAttribute('src', 'http://www.mfiles.co.uk/mp3-downloads/Toccata-and-Fugue-Dm.mp3');

这里有一个JSFiddle,展示了结果。如果你在Chrome中打开网络选项卡,你会发现下载直到开始播放mp3文件才开始。

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