开发者

playing a looping sound when button is pressed in android

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(开发者_如何学C);

 }
}

    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 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.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜