創(chuàng)建SoundPool對(duì)象
// 參數(shù)一:最多同時(shí)播放多少個(gè)音頻。
// 參數(shù)二:音頻類型,有STREAM_MUSIC等,用于區(qū)分音量控制。
// 參數(shù)三:采樣率轉(zhuǎn)換品質(zhì),不起作用,傳入0。
SoundPool soundPool = new SoundPool(/* 數(shù)字 */, AudioManager.STREAM_MUSIC, 0);
加載音頻
private void load(Sound sound) throws IOException {
// openFd可能會(huì)拋出異常
AssetFileDescriptor assetFileDescriptor = mAssetManager.openFd(/* 相對(duì)于Assets文件路徑的文件路徑(包含文件名字和拓展名) */);
// 獲取音頻Id,音頻Id用于播放
int soundId = mSoundPool.load(assetFileDescriptor, /* 暫時(shí)沒有作用,傳入1用于未來的兼容 */);
sound.setSoundId(soundId);
}
播放音頻
if (soundId == null) {
return;
}
// 參數(shù)1:音頻ID
// 參數(shù)2、3:左右音量,(range = 0.0 to 1.0)
// 參數(shù)4:優(yōu)先級(jí),無作用傳入1,用于未來兼容
// 參數(shù)5:循環(huán)模式,(0 = no loop, -1 = loop forever)
// 參數(shù)6:播放速率,(1.0 = normal playback, range 0.5 to 2.0)
mSoundPool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
釋放SoundPool
使用完SoundPool
后需要釋放。
BeatBox.java
public void release() {
mSoundPool.release();
}
BeatBoxFragment.java
@Override
public void onDestroy() {
super.onDestroy();
mBeatBox.release();
}