在android中按下按钮时播放循环声音

时间:2010-10-12 20:36:10

标签: android ontouchlistener

我的问题很简单。我只想在按下按钮时播放循环声音。以下是switch语句,如果我尝试了其他方法。充其量,我可以播放声音但不再按下按钮时不会暂停。

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

2 个答案:

答案 0 :(得分:1)

尝试在true结束时返回false而不是onTouch

现在发生的事情(可能)是你得到一个ACTION_DOWN事件来启动你的声音。通过返回false,您告诉框架您没有使用该操作,这意味着您不会消耗将来的操作。因此,它将停止向您的视图发送触摸事件。

android-developers的相关引用:

  

当您收到ACTION_DOWN事件时,   你回来了吗?如果没有,这个   可能是个问题。框架   只会提供未来的触摸事件   (ACTION_MOVEs和ACTION_UP)来   查看其触摸侦听器或   onTouchEvent返回true。

答案 1 :(得分:0)

将你的mp移到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();
}
相关问题