0

I have a Xamarin.Forms application running on both iOS and Android currently I have discovered an issue with playing sounds inside my app while there is background audio already playing. iOS was easy enough to solve by detecting the presence of AVAudioSession.SharedInstance().OtherAudioPlaying.

I am stumped on whether it is possible to detect if anything is already playing audio on Android. I seem to be able to discover how to play audio in the background but nothing on how to check if there is existing audio playing. Currently both the background audio and my sounds play together which can leave a rather unpleasant experience.

Bijington
  • 3,661
  • 5
  • 35
  • 52
  • 1
    https://developer.android.com/guide/topics/media-apps/audio-focus – Jason Sep 06 '21 at 20:07
  • 1
    check this stackoverflow answer - https://stackoverflow.com/questions/32441833/how-to-detect-an-application-is-playing-audio-or-recording – Nikhil Jain Sep 06 '21 at 20:22
  • @Jason thanks. I didn't want to grab focus but your link helped me to discover the answer which I will post shortly. – Bijington Sep 06 '21 at 20:46
  • @NikhilJain thanks. The second answer on that post actually looks closer to what I needed. – Bijington Sep 06 '21 at 20:46

1 Answers1

0

It turns out it is pretty much as simple as the iOS approach so long as you know the right place to look :). Thanks to the commenters I found that IsMusicActive is available on the Android.Media.AudioManager class. Therefore my solution looks like:

public class AudioHelper : IAudioHelper
{
    public static void Init(Activity activity)
    {
        audioManager = (Android.Media.AudioManager)activity.GetSystemService(Activity.AudioService);
    }

    private static Android.Media.AudioManager audioManager;

    public bool IsOtherAudioPlaying => audioManager?.IsMusicActive == true;
}
Bijington
  • 3,661
  • 5
  • 35
  • 52