my problem is a simple one. i want to play a looping sound only when a button is pressed. the following are the switch statement and if else approaches i’ve tried. at best, i can play the sound but it won’t pause when the button is no longer pressed.
public boolean onTouch(View v, MotionEvent event) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.clash);
if (v.getId() == R.id.clash && event.getAction() == MotionEvent.ACTION_DOWN){
mp.setLooping(true);
mp.start();
}else if (v.getId() == R.id.clash && event.getAction() == MotionEvent.ACTION_UP)
{mp.pause();
}
}
public boolean onTouch(View v, MotionEvent event) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.clash);
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
mp.setLooping(true);
mp.start();
case MotionEvent.ACTION_UP:
mp.pause();
}
return false;
}
Try returning
trueinstead offalseat the end ofonTouch.What’s (probably) happening right now is that you get an
ACTION_DOWNevent which starts your sound. By returningfalseyou tell the framework that you did not consume the action, which it takes to mean that you will not consume future actions, either. Thus, it will stop sending touch events to your view.Relevant quote from android-developers: