Plugin.Maui.Audio plays sound even if Android device is set to vibrate

I have a MAUI application which alerts the user with a sound and vibration when a task is completed. I noticed that turning the phone to vibrate didn’t actually stop the sound being played via the Plugin.Maui.Audio (as I sort of expected it to do).

It looks like what we need to do is write some Android specific code to check the Android AudioManager’s RingerMode.

If we assume we have a device independent enum such as the following (this simply mirrors the Android RingerMode)

public enum AudioMode
{
    Silent = 0,
    Vibrate = 1,
    Normal = 2
}

Now, from our Android code we would expose the RingerMode like this

if (Context.GetSystemService(AudioService) is not AudioManager audioService)
  return AudioMode.Normal;

switch (audioService.RingerMode)
{
  case RingerMode.Normal:
    return AudioMode.Normal;
  case RingerMode.Silent:
    return AudioMode.Silent;
  case RingerMode.Vibrate:
    return AudioMode.Vibrate;
}

return AudioMode.Normal;

Now we would simply wrap our Plugin.Maui.Audio code in an if statement, checking the AudioMode of the device. i.e. if Vibrate or Silent, don’t play the audio. For example

if (_deviceAudioService.AudioMode == AudioMode.Normal)
{
  var audioPlayer =
    _audioManager.CreatePlayer(await FileSystem.OpenAppPackageFileAsync("chimes.wav"));
  audioPlayer.Volume = Math.Clamp(_configuration.NotificationSoundVolume / 100.0, 0, 1);
  audioPlayer.Play();
}