Preload MP3 File before using the Play button

僤鯓⒐⒋嵵緔 提交于 2019-12-12 08:54:32

问题


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!


回答1:


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/




回答2:


You can use the HTML5 <audio> element's preload attribute, and fall back on <embed>.



来源:https://stackoverflow.com/questions/8436633/preload-mp3-file-before-using-the-play-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!