項(xiàng)目中需要用到語音提示,且都是比較簡短的語音提示,剛開始的時(shí)候用的是MediaPlayer進(jìn)行語音播放,但是查閱資料發(fā)現(xiàn)MediaPlayer主要是用來進(jìn)行長音頻播放,且資源消耗較高,后發(fā)現(xiàn)SoundPool進(jìn)行語音播放時(shí)資源消耗更少,且響應(yīng)速度更快,就寫了一個(gè)簡單的SoundPool工具類,主要是用來進(jìn)行短音頻播放,還可以判斷當(dāng)前是否有音頻正在播放。
工具類代碼如下:
/**
* 簡短音頻播放工具類
*/
public class SoundPoolUtil {
private volatile static SoundPoolUtil client;
private SoundPool mSoundPool;
private AudioManager mAudioManager;
/*允許同時(shí)播放的音頻數(shù)(為1時(shí)會(huì)立即結(jié)束上一個(gè)音頻播放當(dāng)前的音頻)*/
private static final int MAX_STREAMS = 1;
// Stream type.
private static final int streamType = AudioManager.STREAM_MUSIC;
private int mSoundId;
private int mResId;
private Context mainContext;
public static SoundPoolUtil getInstance(Context context) {
if (client == null)
synchronized (SoundPoolUtil.class) {
if (client == null) {
client = new SoundPoolUtil(context);
}
}
return client;
}
private SoundPoolUtil(Context context) {
this.mainContext = context;
mAudioManager = (AudioManager) this.mainContext.getSystemService(Context.AUDIO_SERVICE);
((Activity) this.mainContext).setVolumeControlStream(streamType);
this.mSoundPool = new SoundPool(MAX_STREAMS, streamType, 0);
}
/**
* 播放音頻
* @param resId 本地音頻資源
*/
public void playSoundWithRedId(int resId) {
this.mResId = resId;
this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
this.mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
playSound();
}
});
}
/**
* 播放音頻,但是當(dāng)前有音頻這正播放中時(shí)不響應(yīng)該次音頻播放
* @param resId 本地音頻資源
*/
public synchronized void playSoundUnfinished(int resId) {
if ( isFmActive()) return;
this.mResId = resId;
this.mSoundId = this.mSoundPool.load(this.mainContext, this.mResId, 1);
mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
playSound();
}
});
}
/**
* 播放音頻文件
*/
private void playSound() {
mSoundPool.play(this.mSoundId, 1.0f, 1.0f, 0, 0, 1f);
}
/**
* 判斷當(dāng)前設(shè)備是否正在播放音頻
*/
private boolean isFmActive() {
if (mAudioManager == null) {
return false;
}
return mAudioManager.isMusicActive();
}
}