以前只知道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開始。 android