概述
播放一般較大內存的音樂,可以用MediaPlayer,但實際中,那些小型的音頻或(如:提示音)或者對響應速度要求較高的音頻就不適合用MediaPlayer,MediaPlayer的響應需要一定時間,而且需要添加線程。
- SoundPool載入音樂文件使用了獨立的線程,不會阻塞UI主線程的操作。但是這裏如果音效文件過大沒有載入完成,我們調用play方法時可能產生嚴重的後果,這裏Android SDK提供了一個SoundPool.OnLoadCompleteListener類來幫助我們瞭解媒體文件是否載入完成,我們重載 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可獲得。
- 從上面的onLoadComplete方法可以看出該類有很多參數,比如類似id,是的SoundPool在load時可以處理多個媒體一次初始化並放入內存中,這裏效率比MediaPlayer高了很多。
- SoundPool類支持同時播放多個音效,這對於遊戲來說是十分必要的,而MediaPlayer類是同步執行的只能一個文件一個文件的播放。
SDK21版本後,SoundPool的創建發生了很大變化,所以在開發中需要進行版本控制。
使用方法
sdk21之前:
創建SoundPool:
SoundPool(int maxStream, int streamType, int srcQuality)maxStream —— 同時播放的流的最大數量
streamType —— 流的類型,一般爲STREAM_MUSIC(具體在AudioManager類中列出)
srcQuality —— 採樣率轉化質量,當前無效果,使用0作爲默認
- 加載音頻:
- 如果要加載多個音頻,需要用到HashMap等,單個音頻,直接傳入load()方法即可
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) //從完整文件路徑名載入
播放音頻:
play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)- 其中leftVolume和rightVolume表示左右音量,priority表示優先級,loop表示循環次數,rate表示速率;而停止則可以使用 pause(int streamID) 方法,這裏的streamID和soundID均在構造SoundPool類的第一個參數中指明瞭總數量,而id從0開始。
sdk21之後:
麻煩很多,在代碼中體現。
代碼
public class MainActivity extends Activity {
private Button mButtonSoundPool;
private SoundPool mPool;
private int voiceID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonSoundPool = (Button) findViewById(R.id.button_sound_pool);
mButtonSoundPool.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPool.play(voiceID,1,1,0,-1,1);
}
});
voiceID = initSoundPool();
}
private int initSoundPool(){
/**
* 21版本後,SoundPool的創建發生很大改變
*/
//判斷系統sdk版本,如果版本超過21,調用第一種
if(Build.VERSION.SDK_INT>=21){
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(2);//傳入音頻數量
//AudioAttributes是一個封裝音頻各種屬性的方法
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);//設置音頻流的合適的屬性
builder.setAudioAttributes(attrBuilder.build());//加載一個AudioAttributes
mPool = builder.build();
}else{
mPool = new SoundPool(2,AudioManager.STREAM_MUSIC,0);
}
//load的返回值是一個int類的值:音頻的id,在SoundPool的play()方法中加入這個id就能播放這個音頻
return mPool.load(getApplicationContext(),R.raw.outgoing,1);
}
}
我們猿類工作壓力大,很需要有自己的樂趣,於是乎,我開通了音樂人賬號,以後的作品將會上傳到我的音樂人小站上。如果這篇博客幫助到您,希望您能多關注,支持,鼓勵我將創作進行下去,同時也祝你能在工作和生活樂趣兩發麪都能出彩!