Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 961
Aximili Avatar asked May 04 '10 04:05

Aximili


3 Answers

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();
        }
    });
});
like image 189
Germán Rodríguez Avatar answered Oct 27 '22 17:10

Germán Rodríguez


Do this in HTML5 like this:

my_sound = $("<audio>", {src:"filename.mp3",preload:"auto"}).appendTo("body");

Then to play it:

my_sound[0].play();
like image 42
Justin Levene Avatar answered Oct 27 '22 15:10

Justin Levene


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.

like image 2
Sasha Chedygov Avatar answered Oct 27 '22 17:10

Sasha Chedygov