Skip to content

Instantly share code, notes, and snippets.

@ivmirx
Last active April 30, 2021 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivmirx/9611f8d90deed37401695fbfcc67307f to your computer and use it in GitHub Desktop.
Save ivmirx/9611f8d90deed37401695fbfcc67307f to your computer and use it in GitHub Desktop.
Detecting when sound is muted with the silent switch on iPhone or iPad for .NET & Xamarin. Useful for text-to-speech because it does not work when a device is in silent mode. Based on https://github.com/moshegottlieb/SoundSwitch
// since there is no API for checking if the silent mode is on, the trick is to play a 50ms silent system sound
// if it takes just a few milliseconds, it means the sound wasn't allowed to play and the silent mode is on
using System;
using Foundation;
using AudioToolbox;
using System.Threading.Tasks;
public class SilentSwitch
{
readonly SystemSound _sound;
public SilentSwitch()
{
// download the file from this gist and put it into the Resources directory of your iOS project
var url = NSBundle.MainBundle.GetUrlForResource("mute", "caf");
_sound = new SystemSound(url);
_sound.IsUISound = true;
}
public async Task<bool> IsEnabled()
{
// using DateTime because Stopwatch is inaccurate in async code
var startTime = DateTime.Now;
await _sound.PlaySystemSoundAsync();
var elapsedTime = DateTime.Now - startTime;
// on iPhone 8 await takes 160-250ms for 50ms-long `mute.caf` but only 3-8ms when the silent switch is on
return elapsedTime.TotalMilliseconds < 50;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment