I am developing an audio record application in android. So if any background music is already playing in the device music player, that should be paused before it starts recordin
You can stop other applications from playing music, by requesting AudioFocus. When you are granted AudioFocus, other apps stop playing music and then you can play/record as per your needs.
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.
}
But, there is only one AudioManager. So, Audio focus is assigned to each application that requests it one by one. This means that if another application requests audio focus, your application will lose it. You will be notified of the loss of audio focus through the onAudioFocusChange handler of the Audio Focus Change Listener (afChangeListener) 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) :
//Lost focus. Stop recording
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
//Gained AudioFocus. Start recording tasks
break;
default: break;
}
}
};
get audioManager and check
audioManager.isMusicActive()
if true
private void toggleNativePlayer(Context context) {
Intent intent = new Intent("com.android.music.musicservicecommand");
intent.putExtra("command", "togglepause");
context.sendBroadcast(intent);
}
and after you finish recording run this code again to start play musig again