jQuery: How do you preload sound?

大城市里の小女人 提交于 2019-12-10 02:29:21

问题


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.


回答1:


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



回答2:


Do this in HTML5 like this:

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

Then to play it:

my_sound[0].play();



回答3:


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.




回答4:


  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;



回答5:


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.



来源:https://stackoverflow.com/questions/2762865/jquery-how-do-you-preload-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!