你可以阻止其他应用程序播放音乐,请求AudioFocus。当您被授予AudioFocus时,其他应用程序会停止播放音乐,然后您可以根据需要播放/录制。
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_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so you can start recording.
}
但是,只有一个AudioManager。所以,音频焦点被分配给每个请求它的应用程序一个接一个。这意味着如果另一个应用程序请求音频焦点,您的应用程序将失去它。通过您请求音频焦点时注册的Audio Focus Change Listener(afChangeListener)的onAudioFocusChange处理程序将通知您音频焦点丢失。
private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS) :
//Lost focus. Stop recording
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
//Gained AudioFocus. Start recording tasks
break;
default: break;
}
}
};