Android中的soundpool小結

來源:互聯網
上載者:User

之前只知道android中可以用mediaplayer播放音樂,原來今天才發現
可以用soundpool,用soundpool可以播一些短的反應速度要求高的聲音,
比如遊戲中的爆破聲,而mediaplayer適合播放長點的。
1. SoundPool載入音樂檔案使用了獨立的線程,不會阻塞UI主線程的操作。但是這裡如果音效檔案過大沒有載入完成,我們調用play方法時可能產生嚴 重的後果,這裡Android SDK提供了一個SoundPool.OnLoadCompleteListener類來協助我們瞭解媒體檔案是否載入完成,我們重載 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可獲得。
2. 從上面的onLoadComplete方法可以看出該類有很多參數,比如類似id,是的SoundPool在load時可以處理多個媒體一次初始化並放入記憶體中,這裡效率比MediaPlayer高了很多。 人人
3. SoundPool類支援同時播放多個音效,這對於遊戲來說是十分必要的,而MediaPlayer類是同步執行的只能一個檔案一個檔案的播放。

使用方法:
1. 建立一個SoundPool

  public SoundPool(int maxStream, int streamType, int srcQuality)

  maxStream —— 同時播放的流的最大數量

  streamType —— 流的類型,一般為STREAM_MUSIC(具體在AudioManager類中列出)

  srcQuality —— 採樣率轉化品質,當前無效果,使用0作為預設值

  eg.

  SoundPool soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

  建立了一個最多支援3個流同時播放的,類型標記為音樂的SoundPool。

2 一般把多個聲音放到HashMap中去,比如
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundPoolMap = new HashMap<Integer, Integer>();  
    soundPoolMap.put(1, soundPool.load(this, R.raw.dingdong, 1));

  soundpool的載入: 女裝品牌熱門排行榜
      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)  //從完整檔案路徑名載入
最後一個參數為優先順序。

3 播放
play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) ,其中leftVolume和rightVolume表示左右音量,priority表示優先順序,loop表示迴圈次數,rate表示速率,如
//速率最低0.5最高為2,1代表正常速度
sp.play(soundId, 1, 1, 0, 0, 1);
  而停止則可以使用 pause(int streamID) 方法,這裡的streamID和soundID均在構造SoundPool類的第一個參數中指明了總數量,而id從0開始。 風之境地 java-javascript 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.