I have an ImageView. When I touch it, the color changes and the censor sound starts playing. When I take off finger from the ImageView, the color is changed again and the sound should stop playing.
Everything works fine but the sound won't stop. I tried to put the stop() method into the OnClickListener but it didn't work.
How can I stop sound when I take off a finger from ImageView?
btn_censor.setOnTouchListener(new OnTouchListener {
@override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
btn_censor.setImageResource(R.drawable.btn_censor_focus);//Change color of the ImageView
//Parameters for sound
float vol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float leftVolume = vol / maxVol;
float rightVolume = vol / maxVol;
int priority = 1;
int loop = -1; //infinite loop
float normal_plaback_rate = 1f;
soundPool.play(censor_ID, leftVolume, rightVolume, priority, loop, normal_playback_rate);//Play the sound
} else if (event.getAction() == MotionEvent.ACTION_UP) {
btn_censor.setImageResource(R.drawable.btn_censor);//Change colour of the ImageView
soundPool.stop(censor_ID);//This should stop the sound
}
return false;
};
};
You should not pass censor_ID for stop(). The follow code works for me:
int streamID;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
streamID = soundPool.play(myLoadedSoundID, 1, 1, 0, 0, 1);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
soundPool.stop(streamID);
}
return true;
}