简体   繁体   English

如何在Javascript中预加载声音?

[英]How to preload a sound in Javascript?

I can preload images easily thanks to the onload function. onload功能,我可以轻松地预加载图像。 But it doesn't work with audio. 但这不适用于音频。 Browsers like Chrome, Safari, Firefox, etc. don't support the onload functions in the audio tag. Chrome,Safari,Firefox等浏览器不支持音频标签中的onload功能。

How do I preload a sound in Javascript without using JS libraries and without using or creating HTML tags? 如何在不使用JS库,不使用或创建HTML标签的情况下在Javascript中预加载声音?

Your problem is that Audio objects don't support the 'load' event. 您的问题是音频对象不支持'load'事件。

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. 取而代之的是,有一个名为“ canplaythrough”的事件并不意味着它已完全加载,但已加载了足够的内容,以当前的下载速率,该事件将在曲目有足够的时间播放时结束。

So instead of 所以代替

audio.onload = isAppLoaded;

try 尝试

audio.oncanplaythrough = isAppLoaded;

Or better yet.. ;) 还是更好。

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

I tried the accepted answer by tylermwashburn and it didn't work in Chrome. 我尝试了tylermwashburn接受的答案,但它在Chrome中不起作用。 So I moved on and created this and it benefits from jQuery. 因此,我继续进行创建,并从jQuery中受益。 It also sniffs for ogg and mp3 support. 它还嗅探对ogg和mp3的支持。 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. 默认值为ogg,因为某些专家表示192KBS ogg文件与320KBS MP3一样好,因此您可以节省40%的所需音频下载。 However mp3 is required for IE9: 但是mp9对于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. 此外:这是一个mp3到ogg的转换器: http : //audio.online-convert.com/convert-to-ogg或您可以使用VLC Media Player进行转换。 Check your mp3 bitrate by right-clicking on the mp3 file (in Windows) and going to the file details. 通过右键单击mp3文件(在Windows中)并转到文件详细信息,检查mp3比特率。 Try to reduce by 40% when selecting your new bitrate for your new 'ogg' file. 为新的“ ogg”文件选择新的比特率时,请尝试降低40%。 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. 另外(这也适用于我),如果您使用VLC Media Player测试音轨,请确保将音量设置为100%或更低,否则您会听到音频降级的声音,并且可能会错误地认为这是压缩的结果。

Depending on your target browsers, setting the prelaod attribute on the audio tag may be sufficient. 根据您的目标浏览器,在audio标签上设置prelaod属性可能就足够了。

//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 参考

Remy came up with a solution for iOS that utilizes the sprite concept: Remy提出了一个使用Sprite概念的iOS解决方案:

http://remysharp.com/2010/12/23/audio-sprites/ 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). 不确定它可以直接解决预加载问题,但具有的优点是您只需要加载一个音频文件(我想这也是一个缺点)。

Did you try making an ajax request for the file? 您是否尝试过对该文件提出ajax请求? You wouldn't show/use it until it was all the way loaded. 在完全加载之前,您不会显示/使用它。

Eg jQuery: How do you preload sound? 例如jQuery:您如何预加载声音? (you wouldn't have to use jQuery). (您不必使用jQuery)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM