13

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.

Aximili
  • 28,626
  • 56
  • 157
  • 216

5 Answers5

17

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();
        }
    });
});
Germán Rodríguez
  • 4,284
  • 1
  • 19
  • 19
  • 3
    It's a fine solution but not working in IE at least not with sound files, because IE is not able to handle binary files correctly and does not trigger the success function, see this issue for further information: http://bugs.jquery.com/ticket/11426 - discovered it just today. – SamiSalami Aug 31 '12 at 13:18
5

Do this in HTML5 like this:

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

Then to play it:

my_sound[0].play();
Justin Levene
  • 1,630
  • 19
  • 17
2

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.

Sasha Chedygov
  • 127,549
  • 26
  • 102
  • 115
0
  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
  • 29,083
  • 12
  • 64
  • 76
  • 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. – Aximili May 04 '10 at 06:59
  • 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 May 05 '10 at 23:00
0

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
  • 7,423
  • 33
  • 35