使用“播放”按钮之前预加载MP3文件 [英] Preload MP3 File before using the Play button

查看:132
本文介绍了使用“播放”按钮之前预加载MP3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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>

点击播放后,MP3会下载,而不是开始播放。但是,它可能需要一段时间,如果它有1 MB。我需要的是预加载(就像你可以用图像做的那样)。因此,当页面加载时,mp3将被流式传输,例如,如果10秒后,用户按下播放按钮,他将不必等到mp3首先被下载,因为它已经被流式传输。

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!

推荐答案

您可以使用< audio />预加载适用于较新的浏览器。设置 autoplay = false 。对于不支持< audio /> 的旧版浏览器,您可以使用< bgsound /> 。要预加载声音,请将音量设置为 -10000

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

这将在浏览器的缓存中获得声音。然后玩它,你可以继续做你正在做的事情< embed /> 。或者,如果您想利用HTML5功能,可以在返回的< audio /> .play() $ c>元素。您甚至可以在< bgsound /> 中添加播放方法:

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

然后像这样使用它:

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

唯一需要注意的是FireFox不支持mp3。您必须将文件转换为ogg。

The only caveat is FireFox doesn't support mp3. You'll have to convert your files to ogg.

工作演示: http://jsfiddle.net/PMj89/1/

这篇关于使用“播放”按钮之前预加载MP3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆