如何在 Javascript 中预加载声音?

发布于 2024-10-21 22:56:40 字数 172 浏览 3 评论 0原文

借助 onload 函数,我可以轻松预加载图像。但它不适用于音频。 Chrome、Safari、Firefox 等浏览器不支持音频标签中的 onload 函数。

如何在不使用 JS 库且不使用或创建 HTML 标签的情况下在 Javascript 中预加载声音?

I can preload images easily thanks to the onload function. But it doesn't work with audio. Browsers like Chrome, Safari, Firefox, etc. don't support the onload functions in the audio tag.

How do I preload a sound in Javascript without using JS libraries and without using or creating HTML tags?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

郁金香雨 2024-10-28 22:56:40

您的问题是音频对象不支持“加载”事件。

相反,有一个名为“canplaythrough”的事件,这并不意味着它已完全加载,而是已加载足够的内容,以当前的下载速率,它将在曲目有足够的时间播放时完成。

所以不要

audio.onload = isAppLoaded;

尝试

audio.oncanplaythrough = isAppLoaded;

或者更好..;)

audio.addEventListener('canplaythrough', isAppLoaded, false);

Your problem is that Audio objects don't support the 'load' event.

Instead, there's an event called 'canplaythrough' that doesn't mean it's fully loaded, but enough of it is loaded that at the current download rate, it will finish by the time the track has had enough time to play through.

So instead of

audio.onload = isAppLoaded;

try

audio.oncanplaythrough = isAppLoaded;

Or better yet.. ;)

audio.addEventListener('canplaythrough', isAppLoaded, false);
苏大泽ㄣ 2024-10-28 22:56:40

我尝试了 tylermwashburn 接受的答案,但它在 Chrome 中不起作用。所以我继续创建了这个,它受益于 jQuery。它还嗅探 ogg 和 mp3 支持。默认值为 ogg,因为一些专家表示 192KBS ogg 文件与 320KBS MP3 一样好,因此您可以节省 40% 的所需音频下载费用。然而 IE9 需要 mp3:

// Audio preloader

$(window).ready(function(){
  var audio_preload = 0;
  function launchApp(launch){
    audio_preload++;
    if ( audio_preload == 3 || launch == 1) {  // set 3 to # of your files
      start();  // set this function to your start function
    }
  }
  var support = {};
  function audioSupport() {
    var a = document.createElement('audio');
    var ogg = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
    if (ogg) return 'ogg';
    var mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
    if (mp3) return 'mp3';
    else return 0;
  }
  support.audio = audioSupport();
  function loadAudio(url, vol){
    var audio = new Audio();
    audio.src = url;
    audio.preload = "auto";
    audio.volume = vol;
    $(audio).on("loadeddata", launchApp);  // jQuery checking
    return audio;
  }
  if (support.audio === 'ogg') {
    var snd1 = loadAudio("sounds/sound1.ogg", 1);  // ie) the 1 is 100% volume
    var snd2 = loadAudio("sounds/sound2.ogg", 0.3);  // ie) the 0.3 is 30%
    var snd3 = loadAudio("sounds/sound3.ogg", 0.05);
        // add more sounds here
  } else if (support.audio === 'mp3') { 
    var snd1 = loadAudio("sounds/sound1.mp3", 1);
    var snd2 = loadAudio("sounds/sound2.mp3", 0.3);
    var snd3 = loadAudio("sounds/sound3.mp3", 0.05);
        // add more sounds here
  } else {
    launchApp(1);  // launch app without audio
  }

// this is your first function you want to start after audio is preloaded:
  function start(){
     if (support.audio) snd1.play();  // this is how you play sounds
  }

});

此外:
这是一个 mp3 到 ogg 转换器:
http://audio.online-convert.com/convert-to-ogg
或者您可以使用 VLC 媒体播放器进行转换。
右键单击 mp3 文件(在 Windows 中)并转到文件详细信息,检查您的 mp3 比特率。为新“ogg”文件选择新比特率时,尝试降低 40%。转换器可能会抛出错误,因此请继续增加大小,直到被接受。当然,测试声音以获得令人满意的质量。另外(这适用于我)如果您使用 VLC 媒体播放器来测试音轨,请确保将音量设置为 100% 或更低,否则您会听到音频质量下降的声音,并且可能会错误地认为这是压缩的结果。

I tried the accepted answer by tylermwashburn and it didn't work in Chrome. So I moved on and created this and it benefits from jQuery. It also sniffs for ogg and mp3 support. The default is ogg because some experts say a 192KBS ogg file is as good as a 320KBS MP3, so you save 40% on your required audio downloads. However mp3 is required for IE9:

// Audio preloader

$(window).ready(function(){
  var audio_preload = 0;
  function launchApp(launch){
    audio_preload++;
    if ( audio_preload == 3 || launch == 1) {  // set 3 to # of your files
      start();  // set this function to your start function
    }
  }
  var support = {};
  function audioSupport() {
    var a = document.createElement('audio');
    var ogg = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
    if (ogg) return 'ogg';
    var mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
    if (mp3) return 'mp3';
    else return 0;
  }
  support.audio = audioSupport();
  function loadAudio(url, vol){
    var audio = new Audio();
    audio.src = url;
    audio.preload = "auto";
    audio.volume = vol;
    $(audio).on("loadeddata", launchApp);  // jQuery checking
    return audio;
  }
  if (support.audio === 'ogg') {
    var snd1 = loadAudio("sounds/sound1.ogg", 1);  // ie) the 1 is 100% volume
    var snd2 = loadAudio("sounds/sound2.ogg", 0.3);  // ie) the 0.3 is 30%
    var snd3 = loadAudio("sounds/sound3.ogg", 0.05);
        // add more sounds here
  } else if (support.audio === 'mp3') { 
    var snd1 = loadAudio("sounds/sound1.mp3", 1);
    var snd2 = loadAudio("sounds/sound2.mp3", 0.3);
    var snd3 = loadAudio("sounds/sound3.mp3", 0.05);
        // add more sounds here
  } else {
    launchApp(1);  // launch app without audio
  }

// this is your first function you want to start after audio is preloaded:
  function start(){
     if (support.audio) snd1.play();  // this is how you play sounds
  }

});

Furthermore:
Here is an mp3 to ogg converter:
http://audio.online-convert.com/convert-to-ogg
Or you can use VLC Media player to convert.
Check your mp3 bitrate by right-clicking on the mp3 file (in Windows) and going to the file details. Try to reduce by 40% when selecting your new bitrate for your new 'ogg' file. The converter may throw an error, so keep increasing the size until is accepted. Of course test sounds for satisfactory quality. Also (and this applied to me) if you are using VLC Media player to test your audio tracks make sure you set the volume at 100% or below or otherwise you'll hear audio degradation and might mistakenly think it is the result of compression.

守护在此方 2024-10-28 22:56:40
//Tested on Chrome, FF, IE6

function LoadSound(filename) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("load-sound").innerHTML = '<embed src="' + filename + '" controller="1" autoplay="0" autostart="0" />';
        }
    }
    xmlhttp.open("GET", filename, true);
    xmlhttp.send();
}

参考

//Tested on Chrome, FF, IE6

function LoadSound(filename) {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("load-sound").innerHTML = '<embed src="' + filename + '" controller="1" autoplay="0" autostart="0" />';
        }
    }
    xmlhttp.open("GET", filename, true);
    xmlhttp.send();
}

Reference

微凉 2024-10-28 22:56:40

根据您的目标浏览器,设置 audio 标记上的“WC3 HTML5 规范”>prelaod 属性可能就足够了。

Depending on your target browsers, setting the prelaod attribute on the audio tag may be sufficient.

廻憶裏菂餘溫 2024-10-28 22:56:40

Remy 提出了一个利用 sprite 概念的 iOS 解决方案:

http://remysharp。 com/2010/12/23/audio-sprites/

不确定它是否直接解决预加载问题,但其优点是您只需要加载一个音频文件(我想这也是一个缺点)。

Remy came up with a solution for iOS that utilizes the sprite concept:

http://remysharp.com/2010/12/23/audio-sprites/

Not sure it directly addresses the preload, but has the advantage that you only need to load one audio file (which is also a drawback, I suppose).

牛↙奶布丁 2024-10-28 22:56:40

您是否尝试对文件发出 ajax 请求?在它完全加载之前,您不会显示/使用它。

例如jQuery:如何预加载声音?(你不会不必使用 jQuery)。

Did you try making an ajax request for the file? You wouldn't show/use it until it was all the way loaded.

E.g. jQuery: How do you preload sound? (you wouldn't have to use jQuery).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文