How to force the HTML5 Audio tag to reload a (changing) file
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();
}
For those trying to change the src
attribute of a source element, I found this spec note .
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly
So lets say you have:
<audio>
<source src='./first-src'/>
</audio>
To modify the src:
<audio src='./second-src'/>
<source src='./first-src'/>
</audio>