對于Android的游戲音效播放,上次Android123已經告訴大家使用SoundPool類來實現,由于本次我們的游戲需要多種音效同時播放所以就選擇了SoundPool類,它和Android提供常規的MediaPlayer類有哪些不同呢?
1. SoundPool載入音樂文件使用了獨立的線程,不會阻塞UI主線程的操作。但是這里Android開發網提醒大家如果音效文件過大沒有載入完成,我們調用play方法時可能產生嚴重的后果,這里Android SDK提供了一個SoundPool.OnLoadCompleteListener類來幫助我們了解媒體文件是否載入完成,我們重載 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可獲得。
2. 從上面的onLoadComplete方法可以看出該類有很多參數,比如類似id,是的SoundPool在load時可以處理多個媒體一次初始化并放入內存中,這里效率比MediaPlayer高了很多。
3. SoundPool類支持同時播放多個音效,這對于游戲來說是十分必要的,而MediaPlayer類是同步執行的只能一個文件一個文件的播放。
SoundPool類使用示例代碼:
view plaincopy to clipboardprint?
SoundPool sp=new SoundPool(8, /*maxStreams*/, AudioManager.STREAM_MUSIC /*streamType*/, 100 /*srcQuality*/) ;
SoundPool sp=new SoundPool(8, /*maxStreams*/, AudioManager.STREAM_MUSIC /*streamType*/, 100 /*srcQuality*/) ;
有關載入音效的方法,有以下幾種方法
view plaincopy to clipboardprint?
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) //從完整文件路徑名載入
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) //從完整文件路徑名載入
我們看到了每個load的重載版本的最后一個參數為優先級,這里用于播放多個文件時,系統會優先處理不過目前Android123提示大家SDK提到了目前并沒有實現,所以沒有實際的效果。
對于播放,可以使用 play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) 而停止則可以使用 pause(int streamID) 方法,這里的streamID和soundID均在構造SoundPool類的第一個參數中指明了總數量,而id從0開始。
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/JavaTiger427/archive/2010/11/25/6034679.aspx
-- 學海無涯