Question

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;
   }
Was it helpful?

Solution

Try returning true instead of false at the end of onTouch.

What's (probably) happening right now is that you get an ACTION_DOWN event which starts your sound. By returning false you 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:

When you get the ACTION_DOWN event, are you returning true? If not, this is probably the issue. The framework will only deliver future touch events (ACTION_MOVEs and the ACTION_UP) to that View if its touch listener or onTouchEvent returns true.

OTHER TIPS

Move your mp outside the onTouch Handler!

MediaPlayer mp;
public boolean onTouch(View v, MotionEvent event) {
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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top