views:

503

answers:

4

I have a website that plays sound when you click a button.

This is how I do it

function PlaySound(soundfile) {
    $('#soundContainer').html("<embed src='/uploads/sounds/" + soundfile + "' hidden=true autostart=true loop=false>");
}

How do you preload the sound file beforehand?

Thank you.

+1  A: 
  1. Make an AJAX request to it. If your server issues proper caching headers (like Expires) it will be stored in the browser cache.

  2. The ugly way:

soundfile = new Image(); 
soundfile.src = /uploads/sounds/" + soundfile;
sanmai
Thanks Sanmai, but I don't think the code works... It seems to download the file when the page is loaded, but redownload it when I click the button.
Did you check for the caching headers? If there is none of them, a client will surely re-download a file. If you're using Apache, take some time and read about **mod_exires**. If not, Google is to help.
sanmai
A: 

There is no such thing as <embed>.

You could use an HTML5 <audio> element without autoplay, and later make it start playing with its play() method.

Nicolás
And also sacrifice IE support.
musicfreak
in my humble opinion, HTML5 is not ready yet to be at the wild world web
GerManson
You can add IE compatibility using <bgsound src="yourmusicfile.mid">. I'd link some examples, but GeoCities is closed.
banzaimonkey
+2  A: 

There are so many better ways to play sound with JavaScript. For my favorite, check out SoundManager. With it, you can simply call soundManager.load to load the sound file preemptively.

musicfreak
+3  A: 

just thinking in the top of my head, can you make an ajax request for the sound file, but dont show the button until file is 100% loaded.

$(document).ready(function() {
    $.ajax({
        url: "soundfile.mp3",
        success: function() {
            $("#play_button").show();
        }
    });
});
GerManson
Perfect! Thanks!