Вы можете вызвать changeAudioFocus (true);
при запуске воспроизведения мультимедиа из приложения.Он создаст OnAudioFocusChangeListener и установит его с помощью AudioManager, и вы получите обратный вызов, когда получите сообщение AUDIOFOCUS_LOSS или AUDIOFOCUS_LOSS_TRANSIENT.
Вы также получаете AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK, который используется для понижения громкости проигрывателя, что делают некоторые медиаплееры, когда вы получаете звук уведомления.
/**
* Used to indicate a transient loss of audio focus where the loser of the audio focus can
* lower its output volume if it wants to continue playing (also referred to as "ducking"), as
* the new focus owner doesn't require others to be silent.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
*/
код
private final OnAudioFocusChangeListener mAudioFocusListener = createOnAudioFocusChangeListener();
private AudioManager mAudioManager = null;
private boolean mHasAudioFocus = false;
private void changeAudioFocus(boolean acquire) {
if (mAudioManager == null)
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
if (mAudioManager == null)
return;
if (acquire) {
if (!mHasAudioFocus) {
final int result = mAudioManager.requestAudioFocus(mAudioFocusListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mAudioManager.setParameters("bgm_state=true");
mHasAudioFocus = true;
}
}
} else if (mHasAudioFocus) {
mAudioManager.abandonAudioFocus(mAudioFocusListener);
mAudioManager.setParameters("bgm_state=false");
mHasAudioFocus = false;
}
}
private OnAudioFocusChangeListener createOnAudioFocusChangeListener() {
return new OnAudioFocusChangeListener() {
int audioDuckLevel = -1;
private int mLossTransientVolume = -1;
private boolean wasPlaying = false;
@Override
public void onAudioFocusChange(int focusChange) {
/*
* Pause playback during alerts and notifications
*/
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
if (BuildConfig.DEBUG) Log.i(TAG, "AUDIOFOCUS_LOSS");
// Pause playback
changeAudioFocus(false);
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (BuildConfig.DEBUG) Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
// Pause playback
pausePlayback();
break;
case AudioManager.AUDIOFOCUS_GAIN:
if (BuildConfig.DEBUG) Log.i(TAG, "AUDIOFOCUS_GAIN: ");
// Resume playback
if (mLossTransientVolume != -1) {
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mLossTransientVolume, 0);
mLossTransientVolume = -1;
}
if (mLossTransient) {
if (wasPlaying && mSettings.getBoolean("resume_playback", true))
play();
mLossTransient = false;
}
break;
}
}
private void pausePlayback() {
if (mLossTransient) return;
mLossTransient = true;
wasPlaying = isPlaying();
if (wasPlaying) pause();
}
};
}