56

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?

2
  • 2
    The only way I know of is using an <embed> with a reference to the sound keeping it invisible and disable auto-play. But if you don't want to add HTML, I'm not sure what else to recommend. -- EDIT: And I know you don't want a library, but this one may be worth checking (10K in size): schillmania.com/projects/soundmanager2 Mar 15, 2011 at 15:04
  • 1
    Thanks Brad, but SoundManager uses Flash! Mar 16, 2011 at 1:08

6 Answers 6

50

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);
7
  • Thanks Tylermwashburn! Finally you've got the solution! It's works for me! Thanks a lot! :-) Mar 21, 2011 at 23:51
  • @Manuel Ignacio López Quintero: i guess this will only work in HTML5, anyway if you want go through this way reading this may help you bit.ly/ebZH3Z Mar 22, 2011 at 11:15
  • 2
    @tylermwashburn Why addEventListener is better?
    – kiewic
    Apr 27, 2012 at 14:34
  • @tylermwashburn What is the difference between this and onload? will this work on iOS? Sep 3, 2012 at 11:58
  • Good solution but problematic for slow connections because of totally dumb predictions.
    – Salman
    Feb 11, 2013 at 17:23
10

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.

2
  • Very helpful, thank you! As far as audio conversion, I've actually been very happy with Audacity (relatively speaking, as it's a free tool). Provides batch processing and is much faster (in theory) than an online tool as it's a local program. audacity.sourceforge.net
    – Mike
    Feb 15, 2013 at 0:48
  • Also, iOS doesn't support OGG
    – The Onin
    Jun 12, 2019 at 13:00
1
//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

4
  • I think the best option is the solution given in the second link. But it uses JQuery. Aren't there a natural way? Mar 18, 2011 at 0:53
  • natural way added ;) let me know. Mar 18, 2011 at 13:02
  • Ok, I'll try this code! Although I think it will be difficult to manage the sound like the images. Why Google, Mozilla, Microsoft doesn't implement the preload like they do with the images? Mar 20, 2011 at 18:10
  • I try your solution but it's doesn't work for me because I've to create the embed tag. I need to use only JS. Thanks for your effort ASeptik! Mar 21, 2011 at 23:51
0

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

0
0

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).

1
0

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).

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.