I am creating an application that will have multiple images on the screen, these images will be buttons and when tapped will play a short sound. I researched this and could only find the current method I am using to play sounds, which does not seem responsive at all. I want that the sound plays quickly and is responsive to many rapid taps. I was unsure if this was even possible in Android.
The code I am using to play my sound is this:
Button sound1;
MediaPlayer firstSound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
firstSound = MediaPlayer.create(SoundActivity.this, R.raw.click);
sound1 = (Button) findViewById(R.id.Sound1);
beaver.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
firstSound.start();
}
});
}
My lag issue could also be perhaps down to the way I am using the media player object? I do feel that this should be smoother on my phone, any suggestions on how to play sounds in Android is appreciated.
Thanks.
Since discovering Sound Pool, I have edited my code to use this and it works perfectly, the new code looks like this:
SoundPool soundPool;
HashMap<Integer, Integer> soundPoolMap;
int soundID = 1;
Button sound1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(soundID, soundPool.load(this, R.raw.click, 1));
sound1 = (Button) findViewById(R.id.bBeaver);
sound1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float leftVolume = curVolume/maxVolume;
float rightVolume = curVolume/maxVolume;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(soundID, leftVolume, rightVolume, priority, no_loop, normal_playback_rate);
}
});
}
Thanks