2017-05-07 85 views
0

實現一個鍵停止聲音我在這裏很新的,我是那種在java中一個新的。我所有關於代碼的知識都基於我在web上爲我的項目找到的東西。所以一方面我知道另一方面,一些困難的東西,我不知道一個簡單的事情。現在我陷入了這種情況。如何發揮和利用的Soundpool

我有按鈕與循環聲音我想要做的是當我觸摸按鈕它應該改變圖像上「button_prees」當我釋放按鈕時,它應該播放聲音,並改變圖像上的「button_on」所以那一刻代碼下面的工作很好,但現在我試圖做倒序。你觸摸相同的按鈕,它改變形象的「button_prees2」當您鬆開按鈕後,除應立即停止播放聲音,改變對「button_off」

如何在下面的代碼實現這個形象?

final Button b1 = (Button) findViewById(R.id.button1); 
     b1.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View view, MotionEvent motionEvent) { 
       switch (motionEvent.getAction()){ 
        case MotionEvent.ACTION_DOWN: 


         b1.setBackgroundResource(R.drawable.button_prees); 

         break; 

        case MotionEvent.ACTION_MOVE: 

         break; 

        case MotionEvent.ACTION_UP: 


         myS.play(s1I, 1, 1, 1, -1, 1); 

         b1.setBackgroundResource(R.drawable.button_on); 

         break; 
       } 
       return true; 
      } 
     }); 

回答

0

您可以使用布爾值作爲Button狀態的標誌。簡單地說,基本上:調用setSoundsOn(...)否則你的標籤,最終可能會說的話是不是以前

boolean soundsOn = false; 
public void setSoundsOn(boolean soundsOn){ 
    this.soundsOn = soundsOn; 
} 

public boolean isSoundsOn(){ 
    return soundsOn; 
} 
... 

// Then for your Button listener: 
onTouch(...) 
if (!isSoundsOn){ 
    // Your above above code to change resources, start playing 
    // EXCEPT 
    case MotionEvent.ACTION_UP: 
    ... 
    setSoundsOn(true); 
    ... 
}else{ 
    // Code to stop etc. 
    // INCLUDING 
    case MotionEvent.ACTION_UP: 
    ... 
    setSoundsOn(false); 
    ... 
} 
... 

理想情況下,你應該確保聲音已成功啓動/停止。希望這有助於...