在我的应用程序中,我正在尝试制作一个按钮,单击此按钮可停止播放音乐的所有其他应用程序。我想要的是类似的,如果我通过一个音乐播放器播放音乐,如果我尝试通过第二个音乐播放器播放其他音乐,则当前的音乐播放器停止,然后第二个音乐播放器启动。我们如何阻止其他应用从当前活动/应用播放音乐?
答案 0 :(得分:39)
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 .
}
音频焦点依次分配给请求它的每个应用。这意味着如果是另一个 应用程序请求音频焦点,您的应用程序将失去它。你会被告知失去的 音频焦点通过音频焦点变化监听器的onAudioFocusChange处理程序 在请求音频焦点时注册
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;
}
}
};
答案 1 :(得分:3)
您需要使用此处文档中的媒体播放器音频焦点实现:
http://developer.android.com/guide/topics/media/mediaplayer.html#audiofocus