0

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

浏览网页和 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 事件?

4

2 回答 2

2

您应该在“case MotionEvent.ACTION_DOWN”的底部插入“ break ”。

于 2013-04-07T18:34:00.547 回答
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;
        }
      });
于 2013-04-08T18:56:58.890 回答