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.
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();
}
});
});
Do this in HTML5 like this:
my_sound = $("<audio>", {src:"filename.mp3",preload:"auto"}).appendTo("body");
Then to play it:
my_sound[0].play();
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.
Make an AJAX request to it. If your server issues proper caching headers (like Expires) it will be stored in the browser cache.
The ugly way:
soundfile = new Image(); soundfile.src = /uploads/sounds/" + soundfile;
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.
精彩评论