一、SoundPool相對(duì)于MediaPlayer的優(yōu)點(diǎn)
1.SoundPool適合 短且對(duì)反應(yīng)速度比較高 的情況(游戲音效或按鍵聲等),文件大小一般控制在幾十K到幾百K,最好不超過1M,
2.SoundPool 可以與MediaPlayer同時(shí)播放,SoundPool也可以同時(shí)播放多個(gè)聲音;
3.SoundPool 最終編解碼實(shí)現(xiàn)與MediaPlayer相同;
4.MediaPlayer只能同時(shí)播放一個(gè)聲音,加載文件有一定的時(shí)間,適合文件比較大,響應(yīng)時(shí)間要是那種不是非常高的場(chǎng)景
二、SoundPool
SoundPool soundPool;
//實(shí)例化SoundPool
//sdk版本21是SoundPool 的一個(gè)分水嶺
if (Build.VERSION.SDK_INT >= 21) {
SoundPool.Builder builder = new SoundPool.Builder();
//傳入最多播放音頻數(shù)量,
builder.setMaxStreams(1);
//AudioAttributes是一個(gè)封裝音頻各種屬性的方法
AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
//設(shè)置音頻流的合適的屬性
attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
//加載一個(gè)AudioAttributes
builder.setAudioAttributes(attrBuilder.build());
soundPool = builder.build();
} else {
/**
* 第一個(gè)參數(shù):int maxStreams:SoundPool對(duì)象的最大并發(fā)流數(shù)
* 第二個(gè)參數(shù):int streamType:AudioManager中描述的音頻流類型
*第三個(gè)參數(shù):int srcQuality:采樣率轉(zhuǎn)換器的質(zhì)量。 目前沒有效果。 使用0作為默認(rèn)值。
*/
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}
//可以通過四種途徑來記載一個(gè)音頻資源:
//1.通過一個(gè)AssetFileDescriptor對(duì)象
//int load(AssetFileDescriptor afd, int priority)
//2.通過一個(gè)資源ID
//int load(Context context, int resId, int priority)
//3.通過指定的路徑加載
//int load(String path, int priority)
//4.通過FileDescriptor加載
//int load(FileDescriptor fd, long offset, long length, int priority)
//聲音ID 加載音頻資源,這里用的是第二種,第三個(gè)參數(shù)為priority,聲音的優(yōu)先級(jí)*API中指出,priority參數(shù)目前沒有效果,建議設(shè)置為1。
final int voiceId = soundPool.load(context, R.raw.sound, 1);
//異步需要等待加載完成,音頻才能播放成功
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (status == 0) {
//第一個(gè)參數(shù)soundID
//第二個(gè)參數(shù)leftVolume為左側(cè)音量值(范圍= 0.0到1.0)
//第三個(gè)參數(shù)rightVolume為右的音量值(范圍= 0.0到1.0)
//第四個(gè)參數(shù)priority 為流的優(yōu)先級(jí),值越大優(yōu)先級(jí)高,影響當(dāng)同時(shí)播放數(shù)量超出了最大支持?jǐn)?shù)時(shí)SoundPool對(duì)該流的處理
//第五個(gè)參數(shù)loop 為音頻重復(fù)播放次數(shù),0為值播放一次,-1為無限循環(huán),其他值為播放loop+1次
//第六個(gè)參數(shù) rate為播放的速率,范圍0.5-2.0(0.5為一半速率,1.0為正常速率,2.0為兩倍速率)
soundPool.play(voiceId, 1, 1, 1, 0, 1);
}
}
});
}