jQuery: How do you preload sound?

Aximili picture Aximili · May 4, 2010 · Viewed 18k times · Source

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.

Answer

Germ&#225;n Rodr&#237;guez picture Germán Rodríguez · May 4, 2010

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