在运行时将Action_Down和_up的onTouch事件添加到按钮以在按下按钮时播放声音

问题描述:

我想在运行时创建按钮。按钮应该在按下时开始播放声音,并在用户停止按下按钮时停止播放。在运行时将Action_Down和_up的onTouch事件添加到按钮以在按下按钮时播放声音

浏览网页和堆栈溢出我想出这个代码:

// 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事件?

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

+0

当然......我很关注与MediaPlayer对象或者说我错过了明显的MotionEvent发现一个问题。 谢谢! 我已更正了代码并将其附加在下面。 – 2013-04-08 18:53:27

+0

我刚刚意识到这只能工作一次。我点击按钮并听到声音循环。我松开按钮,播放立即停止。一个也必须添加mp.reset();在mp.stop()之后; – 2013-04-08 19:51:26

正确的代码是:

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