检测用户是否正在播放来自其他应用的音乐

时间:2017-06-03 20:02:48

标签: c# android ios unity3d audio-player android-music-player

我的游戏有一个游戏中的音轨,如果用户正在Android或iOS上的媒体应用播放他们自己的音乐,我想暂停音乐。

有没有办法做到这一点,足以在update()函数中运行?

提前致谢!

2 个答案:

答案 0 :(得分:4)

您可以按照this发布的说明检查音乐是否正在播放。

AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or do it not
 }

用Java编写一个类,然后在AndroidJavaClass API的帮助下从C#中调用它。

但这需要Java。您可以将该代码转换为C#而无需Java。获取UnityPlayerPlayer,然后获取Context。其余的可由AndroidJavaClass处理。

以下是不需要Java插件的移植C#版本。

bool isMusicPlaying()
{
    const string 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;
}

答案 1 :(得分:1)

您必须实现回调onAudioFocusChange(),当其他应用获取或放弃音频焦点时,您的应用会收到该回调。

AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                         // Use the music stream.
                         AudioManager.STREAM_MUSIC,
                         // Request permanent focus.
                         AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback
}

回调本身:

AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {

public void onAudioFocusChange(int focusChange) {
  if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
    // Permanent loss of audio focus
    // Pause playback immediately
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
    // Pause playback
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
    // Lower the volume, keep playing
  } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
    // Your app has been granted audio focus again
    // Raise volume to normal, restart playback if necessary
  }
}

查看此官方指南:Handling Changes in Audio Output