Chen Li Yong
Chen Li Yong

Reputation: 6107

How to save audio files on browser's cache so that when the user press a button, the audio starts playing immediately from cache?

I have a collection of short audio files, and I want to play one audio file when the user press a corresponding button. I have this script to play a sound:

<script type="text/javascript">
    var sound = new Audio();
    function playSound(audioUrl) {
        sound.src = audioUrl;
        sound.play();
    }
</script>

<button type="button" onclick="playSound('http://example.com/audioA.mp3')">Audio A</button>
<button type="button" onclick="playSound('http://example.com/audioB.mp3')">Audio B</button>
<button type="button" onclick="playSound('http://example.com/audioC.mp3')">Audio C</button>
...

The problem is, these audio files are not large, but still need a short delay to download and play at the first time the button pressed, which kinda annoying. How do I command the browser to cache all the audio files on page load? When I search about this I found about buffering and streaming audio, which might not suit my needs as my audio lengths are not that long. Thanks.

Upvotes: 10

Views: 10390

Answers (2)

Andy
Andy

Reputation: 403

Alternatively, you could also use .load() to pre-load the files and then play them like you did it in the code above.

Upvotes: 4

Mouser
Mouser

Reputation: 13304

You can preload them and then make the link available as soon is preloading is complete. You can do this synchronous or asynchronous. I recommend to do it asynchronous.

Look at this example:

var sound = new Audio();
function playSound(audioUrl) {
  sound.src = audioUrl.getAttribute('data-url'); //grab the data-url
  sound.play();
}

function preloadAudio()
{
  var audioButtons = document.querySelectorAll("button[data-type='audio']") //select all button elements with data-type = audio
  for (var i = 0; i < audioButtons.length; i++)
  {
    //loop all audio elements
    audioButtons[i].setAttribute("disabled", true); //disable the element
    var preloader = new Audio();
    preloader.addEventListener("loadeddata", enableAudioButton.bind(audioButtons[i]), true); // use bind to link the audio button to the function
    preloader.src = audioButtons[i].getAttribute("data-url"); //trigger the download
  }
}

function enableAudioButton()
{
  this.removeAttribute("disabled");  //reenable the button
}

document.body.addEventListener("load", preloadAudio, true);
<button type="button" data-type="audio" data-url="http://example.com/audioA.mp3" onclick="playSound(this)">Audio A</button>
<button type="button" data-type="audio" data-url="http://example.com/audioB.mp3" onclick="playSound(this)">Audio B</button>
<button type="button" data-type="audio" data-url="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" onclick="playSound(this)">Audio C</button>

I've used a real example (audio C), so you can see the script in function.

Upvotes: 5

Related Questions