简体   繁体   中英

Javascript: How to load updated audio file and play it

I am trying to play one audio file and so far I am able to do it by:

a = new Audio("audio.mp3");
a.load();
a.play();

But after playing it what I am trying to do is that I am creating new audio file with same name. Now again when I click one button and run this function to play audio, then it will play the previous file output rather than new one. So how I can re-upload the same file with same name so that new audio will be generated.

Thanks

The reason you keep getting the same audio file because of the browser cache, Since it's the same name the browser assumes the two files are the same. To prevent this, you can append a random query string to the filename so the browser thinks that you have a new file every time. But the down side of this is your user have to download the audio file every time, this could slow down your user loading time.

a = new Audio("audio.mp3?random=" + new Date().getTime());
a.load();
a.play();

If you have access to the uploaded time you can append that datetime instead of a random datetime, at least that force the browser to download the file only once per upload.

a = new Audio("audio.mp3?random=" + uploadDate.getTime());
a.load();
a.play();

In case to load another file with the same name (or even maybe with another name, in the same object), you need to remove the previous Object! a.remove() will do the trick:

a = new Audio('a.mp3');
    a.load();
    a.play();
    setTimeout(function(){a.pause();a.remove();a.load('a.mp3');a.play();},10000);

the above code loads a.mp3 plays it for 10 seconds. After 10 seconds it loads a.mp3 again whit what ever content there is in that file.

You need to be fast enough to replace the audio file with the same name in 10 seconds :D (or just raise the timeout seconds)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM