Reputation: 3673
I have a requirement in one of my app in which I need to play an audio for a while on click of a button.
Now there comes a case if user is already playing music on device, then i need to pause that music player to play my sound and after I release my MediaPlayer
object I want to resume other app's(or atleast system's) music player.
What I have managed to do is to gain audio focus like below -
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (am!=null){
am.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener()
{
@Override
public void onAudioFocusChange(int focusChange) {
}},
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
}
But this snippet completely stops other app's music player and after releasing my MediaPlayer
object AudioService
is not giving focus back to system's music player.
Upvotes: 1
Views: 1313
Reputation: 2265
Use this :
public void musicPause() {
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive()) {
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause"); // you can give command here play,pause,resume and stop
playVideo.this.sendBroadcast(i); // playVideo is my Activity name
}
}
Upvotes: 0
Reputation: 898
You can use this code. For more info about onAudioFocusChangeListener
onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS):
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
pause();
break;
case (AudioManager.AUDIOFOCUS_GAIN):
resume();
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
player.setVolume(0.1f, 0.1f);
break;
}
}
};
int mediaresult = audioManager.requestAudioFocus(onAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (mediaresult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//other app stop music you can play now
//put you play code here..
}
Upvotes: 1