Waiting for SoundPool to load

While SoundPool is the best tool for handling short sound clips that are frequently used, it does have the problem that the sound is often not played first time. This is because the load into the pool has not finished. There will be a simple log message saying, ‘sample x not ready.’ The solution I have used is to implement an OnLoadCompleteListener.

		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
		try {
			AssetManager assetManager = getAssets();
			AssetFileDescriptor descriptor1 = assetManager.openFd("beep-01a.mp3");
			beepId1 = soundPool.load(descriptor1, 1);
		        AssetFileDescriptor descriptor2 = assetManager.openFd("beep-07.mp3");
			beepId2 = soundPool.load(descriptor2, 1);
		} catch (IOException e) {
			Log.d("Couldn't load sound effect from asset, " + e.getMessage(), null);
		}
		soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
			@Override
			public void onLoadComplete(SoundPool arg0, int arg1, int arg2) {
				playBeep1();
			}
            
        });

Thanks to DZone for the background and the solution options and Vogella for an example.

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *