Ujjwal Syal
Ujjwal Syal

Reputation: 387

How to stop other apps playing music from my current activity?

In my app I am trying to make a button which when clicked stops all other apps that are playing music. What I want is similar to that if I am playing music through one music player and if I try playing some other music through a second music player, the current music player stops and then the second one starts. How do we stop other apps playing music from current activity/app?

Upvotes: 20

Views: 19289

Answers (3)

Nijat Ahmadli
Nijat Ahmadli

Reputation: 899

Since the requesting audio focus and pausing ongoing audio behaviour varies depending on Android versions this answer aims to provide a complete solution based on the docs

To begin with requesting audio focus can automatically stop (fade out) an ongoing audio only on Android versions 12 and later. There is also automatic ducking feature introduced started from Android 8 but for my use case it was not useful as I wanted to stop any background audio completely. So I treated this as an audio conflict and asked user to manually stop any background music before proceeding with the feature.

To request audio focus you can use this method which takes into account different Android versions for compatibility:

private val audioChangeListener = AudioManager.OnAudioFocusChangeListener {
    when (it) {
        AudioManager.AUDIOFOCUS_LOSS,
        AudioManager.AUDIOFOCUS_LOSS_TRANSIENT,
        AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
            // Audio focus is lost. Depending on the use case stop playing or ask user to stop any ongoing audio manually and try again
        }
    }
}

private fun requestAudioFocus(): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        requestAudioFocusForAndroidOreoAndAbove()
    } else {
        requestAudioFocusForBelowAndroidOreo()
    }
}

@RequiresApi(Build.VERSION_CODES.O)
private fun requestAudioFocusForAndroidOreoAndAbove(): Boolean {
    audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN).run {
        setAudioAttributes(
            AudioAttributes.Builder().run {
                setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
                setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                build()
            }
        )
        // In case any other app requests focus we want to be notified instead of getting ducked
        setWillPauseWhenDucked(true)
        setOnAudioFocusChangeListener(audioChangeListener)
        build()
    }

    return audioManager.requestAudioFocus(audioFocusRequest!!) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}

private fun requestAudioFocusForBelowAndroidOreo(): Boolean {
    val result = audioManager.requestAudioFocus(
        audioChangeListener,
        AudioManager.STREAM_VOICE_CALL,
        AudioManager.AUDIOFOCUS_GAIN
    )

    return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
}

Then if you want to request audio focus and check if it was successful and it was possible to stop the ongoing audio, you can use this method:

fun requestAudioFocusIfPossible(): Boolean {
    if (audioManager.isMusicActive && !canStopActiveMusic()) {
        return false
    }

    return requestAudioFocus()
}

/**
 * For Android 12 and higher the fade out behavior happens when the following conditions are met
 * https://developer.android.com/guide/topics/media-apps/audio-focus#audio-focus-12
 */
private fun canStopActiveMusic(): Boolean {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        audioManager.activePlaybackConfigurations.forEach {
            return it.audioAttributes.contentType != AudioAttributes.CONTENT_TYPE_SPEECH &&
                it.audioAttributes.usage in listOf(
                AudioAttributes.USAGE_MEDIA, AudioAttributes.USAGE_GAME
            )
        }
    }

    return false
}

Upvotes: 0

Pranav Jadav
Pranav Jadav

Reputation: 773

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

Audio focus is assigned in turn to each application that requests it. This means that if another application requests audio focus, your application will lose it. You will be notifi ed of the loss of audio focus through the onAudioFocusChange handler of the Audio Focus Change Listener 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_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;
}
}
};

Upvotes: 47

petey
petey

Reputation: 17150

You need to use the media players audio focus implementations found in the docs here:

http://developer.android.com/guide/topics/media/mediaplayer.html#audiofocus

Upvotes: 3

Related Questions