private AudioManager mAudioManager;
private AudioManager.OnAudioFocusChangeListener mFocusChangeListener;
@Override
protected void onPause() {
super.onPause();
stopPlayVoice();
}
@Override
protected void onResume() {
super.onResume();
startPlayVoice();
}
public void stopPlayVoice() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
mFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
}
};
}
for (int i = 0; i < 10; i++) { //尝试10次请求AudioFocus,一般一两次可以请求到,一旦请求到,语音将暂停播放
if (mAudioManager.requestAudioFocus(mFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
break;
}
SystemClock.sleep(100);
}
}
private void startPlayVoice() {
if (mAudioManager != null) {
mAudioManager.abandonAudioFocus(mFocusChangeListener);//放弃并还回拿到的AudioFocus,语音将继续播放
}
}