Detecting If User Is Playing Music From Another App
My game has an in-game soundtrack and I would like to pause the music if the user is playing music of their own from a media app on Android or iOS. Is there a way to do this that i
Solution 1:
You can check if music is playing as described from this post.
AudioManagermanager= (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
{
// do something - or do it not
}
Wrap it around a class in Java then call it from C# with the help of the AndroidJavaClass
API.
But that requires Java. You can take that code and convert it to C# without Java at-all. Get UnityPlayerPlayer, Activity then the Context. The rest can be handled by AndroidJavaClass
.
Here is the ported C# version that does not require Java plugin.
boolisMusicPlaying()
{
conststring AUDIO_SERVICE = "audio";
AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");
bool mIsPlaying;
using (AndroidJavaObject audioManager = unityContext.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
{
mIsPlaying = audioManager.Call<bool>("isMusicActive");
}
return mIsPlaying;
}
Solution 2:
You have to implements the callback onAudioFocusChange() that your app will receive when some other app acquires or abandons audio focus.
AudioManageram= (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playbackintresult= am.requestAudioFocus(afChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Start playback
}
And the callback itself:
AudioManager.OnAudioFocusChangeListenerafChangeListener=newAudioManager.OnAudioFocusChangeListener() {
publicvoidonAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// Permanent loss of audio focus// Pause playback immediately
} elseif (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
// Pause playback
} elseif (focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume, keep playing
} elseif (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Your app has been granted audio focus again// Raise volume to normal, restart playback if necessary
}
}
Take a look on this official guide: Handling Changes in Audio Output
Post a Comment for "Detecting If User Is Playing Music From Another App"