views:

69

answers:

2

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;
   }
A: 

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.

eldarerathis
thanks for the reply. i did switch to true but i still have the same problem.
strangeInAStrangerLand
@Puzzled: Can you see `ACTION_DOWN` being fired in logcat? Is this a custom view? I just noticed that your `onTouch` method doesn't appear to be an override.
eldarerathis
the logcat is completely blank. i have no idea why but i never see anything in it. this is not a custom view. just a simple button.
strangeInAStrangerLand
i found out why the logcat was blank. here's the complete log. and no, it isn't showing ACTION_DOWN being fired.
strangeInAStrangerLand
A: 

10-12 21:48:52.081: DEBUG/AudioSink(34): bufferCount (4) is too small and increased to 12 10-12 21:48:52.392: ERROR/MediaPlayer(738): pause called in state 8 10-12 21:48:52.392: ERROR/MediaPlayer(738): error (-38, 0) 10-12 21:48:52.392: WARN/MediaPlayer(738): mediaplayer went away with unhandled events 10-12 21:48:52.392: WARN/MediaPlayer(738): mediaplayer went away with unhandled events 10-12 21:48:52.392: WARN/MediaPlayer(738): mediaplayer went away with unhandled events

this is the portion of the log that fires off with i press the button.

strangeInAStrangerLand