admin管理员组

文章数量:1313111

In the document.ready function, I have this:

audioElement = document.createElement('audio');

audioElement.setAttribute('src', '.mp3');

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

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

The problem is that the MP3 is downloaded when the page loads, which causes significant load time since the MP3 is over 2MB. What I want is the MP3 to be streamed. Is this possible and if so, what do I need to change?

jsFiddle here

In the document.ready function, I have this:

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();
});

The problem is that the MP3 is downloaded when the page loads, which causes significant load time since the MP3 is over 2MB. What I want is the MP3 to be streamed. Is this possible and if so, what do I need to change?

jsFiddle here

Share Improve this question edited Jun 14, 2014 at 15:46 frenchie asked Jun 14, 2014 at 15:44 frenchiefrenchie 52k117 gold badges319 silver badges527 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9 +50

You're very close to getting it right. I've had a look at your JSFiddle and noticed that the audio does stream already (I can play the file before it's finished downloading). You can easily see this by checking the Network traffic in your browser:

Chrome displays 'partial content' but is playing the mp3 at the same time. Your specific problem seems to be that it is downloading and playing too early. So if we take a look a the spec we can see some options.

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.

As you're not displaying any information about the audio file we can ignore the metdata option, this means you want to set the preload="none" attribute. Therefore if you change your JSFiddle slightly to dynamically set this:

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

Here is a JSFiddle showing the result, if you bring up the network tab in Chrome you'see see that the download doesn't start till you begin playing the mp3.

本文标签: javascriptStreaming MP3 instead of downloading it with HTML5 audio tagStack Overflow