-1

I have an application that launches a stream, if i turn on the music playback in any other application then it plays the two tracks in parallel. How can I prevent this?

jclozano
  • 618
  • 6
  • 24

1 Answers1

0

Take a look at this question.

Basically, you can't stop other applications from playing their audio. You can however, be alerted when another application begins playing audio, and react accordingly. All credit for this answer goes to Pranav Jadav.

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;
        }
    }
};
Community
  • 1
  • 1
Kenny Worden
  • 4,335
  • 11
  • 35
  • 62
  • added listener to AudioManager and its works great. AudioManager manager = (AudioManager) getSystemService(AUDIO_SERVICE); manager.requestAudioFocus(mAudioFocusChangeListener , AudioManager.STREAM_MUSIC , AudioManager.AUDIOFOCUS_GAIN); Thank You! – Artem Taranovskiy Feb 11 '16 at 09:52