The code below is to click an Image button with some animation, at the same time it with a sound effect. Problem is the sound track doesn't match with the button click when I repeat clicking the button, the sound effect delayed and doesn't match with the number of clicking.
[Class file] // the sound track get from res/raw/track.mp3
final MediaPlayer click= MediaPlayer.create(this, R.raw.track);
btn1= (ImageButton) findViewById(R.id.btn1);
txt1= (TextView) findViewById(R.id.txt1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate));
click.start();
}
});
You might want to consider using a SoundPool
.
Try this:
SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
HashMap<Integer, Integer> soundPoolMap soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(soundID, soundPool.load(this, R.raw.your_sound, 1));
And then play your sound using
soundPool.play(soundId, 1, 1, 1, 0, 0);
This answer is linked to this post:POST