0

My app contains audio. And when some other app (radio, music, ...) is playing in background mode, sounds of my app are playing above (together) with that app. Is there any ability to stop that music app, when my app is playing? Or maybe mute it or smth else.

Lemoon
  • 3
  • 2

1 Answers1

1

i faced this before and that was the solution

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 .
}


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;
}}};