An overview of the SoundPool

A sound player helper class, as its name suggests, has “pooling” capabilities (caching) that load sound files into memory first to support multiple playback of sound files.

The characteristics of

  • SoundPool is good for short sound files
  • SoundPool is suitable for playing “prompts that need to be played many times”, such as in some common login, please click what
  • It uses less resources than mediaPlayer
  • Multiple sounds can be played simultaneously

Method of use

Create an instance

mSoundPool = new SoundPool(1, AudioManager.STREAM_ALARM, 0); soundPoolMap = new HashMap<Integer, Integer>(); // Here I create a hash table to record the ID of the loaded sound. Normally we define a constant as the KEY to retrieve the soundCopy the code

Loading sound files

soundPoolMap.put(KEY_SOUND_A1, mSoundPool.load(this, R.raw.a1, 1)); soundPoolMap.put(KEY_SOUND_A2, mSoundPool.load(this, R.raw.a2, 1)); // Note that the hash table contains recordsCopy the code

Play a sound file

mSoundPool.play(soundPoolMap.get(KEY_SOUND_A1), 1, 1, 0, 0, 1); // Notice that the specific ID is extracted from the hash tableCopy the code

Register a listener to get a message when the sound is finished loading

mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { alert(" " + sampleId); }});Copy the code

code

Below is the complete code for the class

package demo.vir56k.soundpooldemo; import android.media.AudioManager; import android.media.SoundPool; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import java.util.HashMap; public class MainActivity extends AppCompatActivity { public static final int KEY_SOUND_A1 = 1; public static final int KEY_SOUND_A2 = 1; SoundPool mSoundPool; private HashMap<Integer, Integer> soundPoolMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSoundPool = new SoundPool(1, AudioManager.STREAM_ALARM, 0); mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { alert(" " + sampleId); }}); soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(KEY_SOUND_A1, mSoundPool.load(this, R.raw.a1, 1)); soundPoolMap.put(KEY_SOUND_A2, mSoundPool.load(this, R.raw.a2, 1)); } private void alert(String s) { Log.i("Alert: ", s + ""); } public void onClickView(View view) { if (view.getId() == R.id.button) { mSoundPool.play(soundPoolMap.get(KEY_SOUND_A1), 1, 1, 0, 0, 1); } if (view.getId() == R.id.button2) { mSoundPool.play(soundPoolMap.get(KEY_SOUND_A2), 1, 1, 0, 0, 1); }}}Copy the code

Download: github.com/vir56k/demo…