在运行期间为Action_Down和_up添加一个onTouch事件,以便在按下按钮时播放声音

时间:2013-04-07 15:35:07

标签: android button media-player ontouchlistener

我想在运行时创建一个按钮。按下该按钮应该在按下时开始播放声音,并在用户停止按下按钮时停止播放。

浏览网页和Stack Overflow我想出了这段代码:

    // Create a new button and place it into a table row
    LinearLayout lnr = (LinearLayout) findViewById(R.id.tableRow3);
    Button b1 = new Button(this);
    lnr.addView(b1);

    // Associate the event
    b1.setOnTouchListener(new OnTouchListener() {
        MediaPlayer mp = new MediaPlayer();
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                // Finger started pressing --> play sound in loop mode
                try {
                    FileInputStream fileInputStream = new FileInputStream( PATH );
                    mp.setDataSource(fileInputStream.getFD());
                    mp.prepare();
                    mp.setLooping(true);
                    mp.start();
                } catch (Exception e) {}
            case MotionEvent.ACTION_UP:
                // Finger released --> stop playback
                try {
                    mp.stop();
                } catch (Exception e) {} 
          }
          return true;
        }
      });   

问题在于我根本听不到声音。在我看来,case MotionEvent.ACTION_UP:是直接触发的。因此,播放将直接停止。

为了测试这个假设,我删除了mp.stop();并听到了无限循环的声音。很明显,它必须是ACTION_UP事件,搞砸了一切。但是,如果我不释放手指/鼠标,怎么能触发ACTION_UP事件?

2 个答案:

答案 0 :(得分:2)

您应该插入' 中断'位于'案例底部的MotionEvent.ACTION_DOWN'。

答案 1 :(得分:1)

正确的代码是:

    // Create a new button and place it into a table row
    LinearLayout lnr = (LinearLayout) findViewById(R.id.tableRow3);
    Button b1 = new Button(this);
    lnr.addView(b1);

    // Associate the event
    b1.setOnTouchListener(new OnTouchListener() {
        MediaPlayer mp = new MediaPlayer();
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                // Finger started pressing --> play sound in loop mode
                try {
                    FileInputStream fileInputStream = new FileInputStream( PATH );
                    mp.setDataSource(fileInputStream.getFD());
                    mp.prepare();
                    mp.setLooping(true);
                    mp.start();
                } catch (Exception e) {}
            break;
            case MotionEvent.ACTION_UP:
                // Finger released --> stop playback
                try {
                    mp.stop();
                    mp.reset();
                } catch (Exception e) {}
            break;
          }
          return true;
        }
      });