0

実行時にボタンを作成したい。ボタンは、ボタンを押すと音の再生を開始し、ユーザーがボタンを押すのをやめると再生を停止する必要があります。

Web とスタック オーバーフローをブラウジングすると、次のコードが思いつきます。

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