2013-04-07 64 views
0

我想在運行時創建按鈕。按鈕應該在按下時開始播放聲音,並在用戶停止按下按鈕時停止播放。在運行時將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事件?

回答

2

您應該在'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

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