Android中使用SoundPool來播放音頻

來源:互聯網
上載者:User

Android中使用SoundPool來播放音頻

今天找素材重做FlappyBird時學習了一下如何為應用設定背景音頻,發現通過封裝SoundPool類就可以很好的做到這一點。


SoundPool類比較適合播放一些類似遊戲音效這種比較短促而且較小的音頻流,並且它支援同時播放多個音頻流,而比較大的音頻更適合用MediaPlayer來播放。

大致講解一下SoundPool類使用時的基本用法:

1. 把要用到的音頻資源通過load()方法載入.

2. 通過建立的SoundPool對象的setOnLoadCompleteListener()方法建立並傳入SoundPool.OnLoadCompleteListener對象。重載public void onLoadComplete(SoundPool arg0, int arg1, int arg2)方法來檢查音訊載入是否成功.

3. 通過play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)方法來播放音頻流.soundID是要播放的音頻號,priority是音訊播放優先順序,loop是播放遍數(-1是無限迴圈播放),rate是播放速率~


下面是重做FlappyBird時封裝的一個播放音訊類,相比全部用MediaPlayer,這種方法播放音效會更加高效:

package com.example.flappy.util;import java.util.HashMap;import android.media.AudioManager;import android.media.SoundPool;import android.widget.Toast;import com.example.flappy.MainActivity;import com.example.flappy.R;/* * SoundPlayer負責音訊播放 */public class SoundPlayer {private SoundPool soundPool;private MainActivity mainActivity;private HashMap map;public SoundPlayer(MainActivity mainActivity) {this.mainActivity = mainActivity;this.map = new HashMap();// SoundPool的建構函式的三個參數分別數:// 1.同時播放的流的最大數量(是同時播放哦)// 2.流的類型// 3.轉化品質this.soundPool = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {@Overridepublic void onLoadComplete(SoundPool arg0, int arg1, int arg2) {// 音頻載入失敗時觸發// 千萬要記得音頻是可能會載入失敗的,一定要在這裡對其做相應的處理}});}public void initSounds() {this.map.put(1, this.soundPool.load(this.mainActivity, R.raw.flappy, 1));this.map.put(2, this.soundPool.load(this.mainActivity, R.raw.pass, 1));this.map.put(3, this.soundPool.load(this.mainActivity, R.raw.hit, 1));this.map.put(4, this.soundPool.load(this.mainActivity, R.raw.die, 1));this.map.put(5, this.soundPool.load(this.mainActivity, R.raw.swooshing, 1));// 就像這樣把你的APP要用到的聲音都載入進來}// 在需要播放音訊地方把要播放的是哪首和要播放的遍數傳進去public void playSound(int sound, int loop) {this.soundPool.play(sound, 1, 1, 1, loop, 1.0f);}public void release() {this.soundPool.release();}}



轉載請註明出處:http://blog.csdn.net/gophers




聯繫我們

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