Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming MP3 instead of downloading it with HTML5 audio tag

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

like image 242
frenchie Avatar asked Dec 21 '25 01:12

frenchie


1 Answers

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:

enter image description here

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.

like image 79
Ian Avatar answered Dec 22 '25 15:12

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!