Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload MP3 File before using the Play button

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!

like image 484
Gabriel Avatar asked Dec 08 '11 19:12

Gabriel


1 Answers

You can preload using <audio /> for newer browsers. Set autoplay = false. For older browsers that don't support <audio />, you can use <bgsound />. To preload a sound, set the volume to -10000.

function preloadSound(src) {
    var sound = document.createElement("audio");
    if ("src" in sound) {
        sound.autoPlay = false;
    }
    else {
        sound = document.createElement("bgsound");
        sound.volume = -10000;
    }
    sound.src = src;
    document.body.appendChild(sound);
    return sound;
}

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 />:

function loadSound (src) {
    var sound = document.createElement("audio");
    if ("src" in sound) {
        sound.autoPlay = false;
    }
    else {
        sound = document.createElement("bgsound");
        sound.volume = -10000;
        sound.play = function () {
            this.src = src;
            this.volume = 0;
        }
    }
    sound.src = src;
    document.body.appendChild(sound);
    return sound;
 }

Then use it like this:

var sound = loadSound("/mySound.ogg");  //  preload
sound.play();

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/

like image 171
gilly3 Avatar answered Sep 21 '22 08:09

gilly3