2013-10-02 65 views
0

我希望能夠在應用程序中點擊按鈕時添加點擊聲音,以及有關如何使行爲適用於整個應用程序的任何建議? 乾杯!如何將聲音添加到Android應用程序中的onClick事件?

+2

您是否嘗試過[Google上搜尋它(https://www.google.com/search?q=Android+play+sound)? –

+0

長/短聲?自定義還是從Android? –

+0

@dotroph,我在前幾次點擊時沒有發現,我的不好。 –

回答

3

在按鈕的onclick,加View.playSoundEffect(SoundEffectConstants.CLICK)

myButton.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      v.playSoundEffect(SoundEffectConstants.CLICK); 
     } 
    }); 
0

或者你可以使用SoundPool對於更復雜的設置(例如,您可以設置左右音量值)

這僅僅是一個例子:

private void playSound() { 
     // TODO Auto-generated method stub  
     SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); 
     // 5 indicates the maximum number of simultaneous streams for this SoundPool object 

     int waterSound = pl.load(this, R.raw.water_sound_01, 0); 
     // is the audio file I have imported in my project as resource 

     pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {    
      @Override 
      public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { 
       // The onLoadComplet method is called when a sound has completed loading. 
       // TODO Auto-generated method stub 
       soundPool.play(sampleId, 1f, 1f, 0, 0, 1); 
       // second and third parameters indicates left and right value (range = 0.0 to 1.0) 
      } 
     }); 
    } 
相關問題