Mute/Silence an iOS device programmatically?

2020-01-27 07:42发布

问题:

I'm trying to mute the device's ringer from within my app, but for some reason using AVSystemController like in this answer ( How to disable iOS System Sounds ) won't let me silence the device ALL the way down.. it drops it to a volume of 1 bar, but not completely silent.

I know it can be done, probably with a private API like AVSystemController, and I know that Apple will still approve the app if the user expects this kind of functionality from the app (since there are already 2 apps I found in the App Store which mutes the device programmatically with no need of jailbreaking or anything like that).

Those apps actually do something better - they actually toggle the actual mute, not just decreasing the volume to zero.

Does anyone know the way this is being done?

Any help will be greatly appreciated! Thanks!

回答1:

This worked for me, I have a button that toggles sound on and off in a game. I set the float to 10 when I want sound on and 0 when I want sound off.

float value = 0.0f;
AudioSessionSetProperty(kAudioSessionProperty_CurrentHardwareOutputVolume, sizeof(float), &value);

Update:

Another option that is still working with iOS 9.1

float vol = [[AVAudioSession sharedInstance] outputVolume];
NSLog(@"output volume: %1.2f dB", 20.f*log10f(vol+FLT_MIN));

For Swift:

let volume = AVAudioSession.sharedInstance().outputVolume   
print("Output volume: \(volume)")

Sources for updates answer: Get System Volume iOS