Wednesday, October 15, 2014

How to Preload Audio in PhoneGap

I just spent days making a simple buzzer in an iOS app!  You push a big red button and it plays a buzzing sound.

Actually, it took about 20 minutes to get it working, but there was a 1-2 second pause after pushing the button before the sound would play, which is unacceptable.

So of course I googled Preload Audio Phonegap and the found a bunch of plugins that claim to do that.  Implementing them was time consuming and no matter what I did I just couldn't get them working.

Then I thought: I wonder what will happen if I just play the file once at zero volume to preload it?

Well, folks, that's all it took.  I feel so foolish for wasting my own time; maybe this post will help you not waste yours.

function playAudio(src, preload) {
  //requires Cordova Core Media plugin
  //src is the path to the file in your www folder
  // for example, audio/buzzer.mp3

        function audioSuccess() {
            console.log("[AUDIO]: Created " + src);
        function audioError(msg) {
            console.log("[AUDIO]: Error " + msg);
        // Create Media object from src
        my_media = new Media(src, audioSuccess, audioError);
        // Play audio
        if (preload === true) {
        } else {