Preload the 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>

As soon as you press the play button, the MP3 will load, and playback will begin. However, this may take some time if it has 1 MB. I need a preload (just like you can do with images). Therefore, when the page loads, mp3 will be broadcast, and if, for example, after 10 seconds, the user clicks the "play" button, he will not have to wait until mp3 is loaded first, since it is already being broadcast.

Any ideas? Thanks in advance for any feedback!

+5
source share
2 answers

<audio /> . autoplay = false. , <audio />, <bgsound />. , -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;
}

. , , , , <embed />. , HTML5, .play() <audio />. <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;
 }

:

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

- FireFox mp3. ogg.

: http://jsfiddle.net/PMj89/1/

+6
+4

All Articles