Search code examples
jqueryaudiopreload

jQuery: How do you preload sound?


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.


Solution

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