Android中SoundPool放聲音

來源:互聯網
上載者:User

標籤:soundpool

      它適合播放那些需要反覆播放,但時間較短的音效。它支援同時播放多種聲音,這些聲音在系統開始時會載入到列表中,按照這些聲音的id,我們可以調用這些音效。

1、建立一個SoundPool對象:new SoundPool(int maxStreams, int streamType, int srcQuality);

第一個參數為soundPool可以支援的聲音數量,這決定了Android為其開設多大的緩衝區,第二個參數為聲音類型,最後參數為聲音品質,品質越高,聲音效果越好,但耗費更多的系統資源。

 

2、從資源或者檔案載入音頻流: 

       int  load(Context context, int resId, int priority)  //從APK資源載入 
       int  load(FileDescriptor fd, long offset, long length, int priority)  //從FileDescriptor對象載入 
       int  load(AssetFileDescriptor afd, int priority)  //從Asset對象載入 
       int  load(String path, int priority)  //從完整檔案路徑名載入 
       priority為優先順序

 

3、播放聲音play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

第一個參數為id,id即為放入到soundPool中的順序,比如現在collide.wav是第一個,因此它的id就是1。第二個和第三個參數為左右聲道的音量控制。第四個參數為優先順序,由於只有這一個聲音,因此優先順序在這裡並不重要。第五個參數為是否迴圈播放,0為不迴圈,-1為迴圈。最後一個參數為播放比率,從0.5到2,一般為1,表示正常播放。

 

 

代碼如下:

  private SoundPool soundPool;

  soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 5);
  final int load = soundPool.load(this, R.raw.wen, 1);
  soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
   public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
    soundPool.play(load, 1, 1, 0, 0, 1);
   }
  });

 

注意點:

  1. SoundPool最大隻能申請1M的記憶體空間,這就意味著我們只能用一些很短的聲音片段,
        而不是用它來播放歌曲或者做遊戲背景音樂。
  2. SoundPool提供了pause和stop方法,但這些方法建議最好不要輕易使用, 因為有些時候它們可能會使你的程式莫名其妙的終止。
  3. SoundPool的效率問題。其實SoundPool的效率在這些播放類中算是很好的了,但是有的朋友在G1中測試它還是有100ms左右的延遲,這可能會影響使用者體驗。

 

Android中SoundPool放聲音

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.