Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

javascript - How to force the HTML5 Audio tag to reload a (changing) file

I have a bit of code in javascript that generates a wav file and then attaches it to a button so it can be played:

function makeWav(){        
            $.get(("../testsound/getsound.pl?text="+document.myform.outputtext.value));
setTimeout(callback, 500);
            return false;
        }
function callback() {
var audio = new Audio('http://www.joereddington.com/testsound/hope.wav');
audio.load();
audio.play();
           //     $("#player").html("<embed src=http://www.joereddington.com/testsound/hope.wav autostart=true  >");
        }

Obviously the hope.wav file changes very regularly. But my problem is that only the first .wav to be generated is played unless I completely reload the site each time. How do I make the (presumably) callback function go and get a new version of the .wav rather than the cache?

EDIT: Works fine on the iPad - I'm having this problem in firefox.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't directly control the caching from within your JavaScript. Retrieving files is the responsibility of the browser, which is why you're getting different results on different browsers.

When a web server sends a file to the browser, it also sends some headers with extra details about that file. One of them is the Cache-Control header, which tells the browser if the file is cacheable. Sending a Cache-Control: no-cache header should stop browsers caching the file, and make subsequent requests retrieve the file from your server.

On Apache, you can use an .htaccess file or a <Directory> rule in your server configuration to change the caching for files in the /testsound directory. Put the following in /testsound/.htaccess:

<ifModule mod_headers.c>
    Header set Cache-Control no-cache
</ifModule>

Another technique is to include a "cache-busting" parameter in your request. Your web server is serving a static file - but your web browser doesn't know that. For all it knows, a request for /testsound/hope.wav?cb=foo could return a completely different file to a request for /testsound/hope.wav?cb=bar. Thus, if you include an always-changing parameter in your web request, the browser won't find it in its cache and it will retrieve the new file. A timestamp is a good choice:

function callback() {
  var url = "http://www.joereddington.com/testsound/hope.wav?cb=" + new Date().getTime();
  var audio = new Audio(url);
  audio.load();
  audio.play();        
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...