If you want to listen sound for a button click corresponding to as many times the user
clicks, specifically when the user clicks/taps continuosly with very short span, then follow below steps :-)
Implement SoundPool and AudioManager classes instead of traditional MediaPlayer. Sample is below:
import
android.content.Context;
import
android.media.AudioManager;
import
android.media.SoundPool;
public class MusicPlayer {
public static SoundPool soundPoolObj;
private static int soundPoolObjectID;
public static AudioManager audioManager;
private static boolean resourceReleased;
/*
* I know you are good enough to catch this,
still....,
*This is the constructor which would be called
*preferably during starting of your app, I mean, before
you start any associated music.
*
*Note that, You have to pass context and resource id for music
to be played.
*
* You may use streaming as well, Since I have not tried any, I
am not posting about it:-)
*/
public
MusicPlayer(Context context,int musicResourceID)
{
resourceReleased=false;
soundPoolObj=new SoundPool(1/*maximum
number of simultaneous streams */,
AudioManager.STREAM_MUSIC,0);
audioManager=(AudioManager)context.getSystemService( Context.AUDIO_SERVICE);
soundPoolObjectID=soundPoolObj.load(context,
musicResourceID, 1/*priority*/);
}
/*
* Invoke
this method to play the corresponding music..
* make sure you have instantiated this class with proper
parameters
*
*/
public static void playMusic()
{
if((!resourceReleased))
{
/*Make sure sound duration is small for click effect..*/
int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
soundPoolObj.play(soundPoolObjectID/*soundID*/,
streamVolume/*leftVolume*/, streamVolume/*rightVolume*/,
1, 0/*loop: '0' for no looping and '-1' for looping forever*/, 1f);
/*
*if you wanna pause a long
background music,
*try: soundPoolObj.pause(soundPoolObjectID);
* and soundPoolObj.resume(soundPoolObjectID); for
resuming
*/
}
}
/*
*Called when you are quitting/ no longer need music
*/
public static void stopMusic()
{
//Finally..
soundPoolObj.stop(soundPoolObjectID);
//Release the associated resource
MusicPlayer.soundPoolObj.release();
resourceReleased=true;
}
}
This is an utility class and needs support from a class which implements Activity.
Happy coding :-)