Search code examples
javaandroidsoundpool

Sound Pool in android


I trying to make an app, with a lot of short sounds(more than 20), using Sound Pool. But when i load that sounds, it take like 3-10 sec to load it. How can i improve speed of loading? Here is Function of loading

private int loadSound(String filename) {
    AssetFileDescriptor assetFileDescriptor;
    try {
        assetFileDescriptor = assetManager.openFd(filename);
    }
    catch (IOException e){
        e.printStackTrace();
        return -1;
    }
   return soundPool.load(assetFileDescriptor,1);
}

Solution

    • Use .OGG files at the lowest sample rate you can tolerate, like 96kb/s. This will create the smallest files so they load faster. I had a lot of problems with loading/playing sounds using .WAV files, they all went away when I converted them to .OGG files.

    • Do your sound loading off the main UI thread. If you need to know when the sound is loaded, use an OnLoadCompleteListener:

      mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
          @Override
          public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
              Log.d(TAG, "soundpool onLoadComplete, sampleId = " + sampleId + ", status = " + status);
      
              // ... sound is ready to play            
          }
      });
      
      // sound load should happen off the UI thread
      new Thread() {
          @Override
          public void run() {
              mSoundId = mSoundPool.load(getActivity(), R.raw.sound1, 1);
              // ... load other sounds here
          }
      }.start();
      

      I embedded the audio files so I could use raw resource ids. If you have to load from files, grab all your filenames and send them off to a load method inside a non-UI thread.