当我启动 MediaPlayer 时,其他正在播放音频的应用程序不会停止。使用 MediaRecorder 时相同。
我设法使用 AudioManager
来获得一些功能,但该类的大部分内容要么已弃用,要么用于高级 API。
例如,我可以注册一个回调,但我不能注销它,因为 abandonAudioFocus()
已被弃用。
查看源代码,它告诉我使用 MediaSession
,但这对于我播放简单录制音频的简单目标来说太复杂了,我不想使用每一个的所有功能安卓平台。
最佳答案
您可以使用AudioManager
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
Audio focus is assigned in turn to each application that requests it. This means that if another application requests audio focus, your application will lose it. You will be notifi ed of the loss of audio focus through the onAudioFocusChange handler of the Audio Focus Change Listener you registered when requesting the audio focus
private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
mediaPlayer.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
pause();
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
stop();
ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
am.unregisterMediaButtonEventReceiver(component);
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
break;
default: break;
}
}
};
关于java - 暂停其他媒体应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53466194/