我知道 Apple 没有提供检测 iOS 5 中 iPhone mute/silence
开关状态的方法。但是,我已经尝试过其他地方提到的一种技术,通过播放音频文件并测量其运行时间来检测这一点。但是,即使我的 iPhone 已静音,音频文件仍会播放整个持续时间。我正在使用 [AVAudioPlayer play]
并计算调用 audioPlayerDidFinishPlaying
之前的时间。您是否知道播放音频文件的技巧,如果手机处于静音状态,该音频文件将提前/立即完成?
最佳答案
更新:抱歉,下面发布的代码对我来说工作正常,但我使用的是 iOS4。对于 iOS5,此答案将解决您的问题 - Detecting the iPhone's Ring / Silent / Mute switch using AVAudioPlayer not working?
这段代码正是您所需要的。定义一个全局 gAudioSessionInited
变量。此标志告诉您静音开关是打开还是关闭。
// "Ambient" makes it respect the mute switch. Must call this once to init session
if (!gAudioSessionInited)
{
AudioSessionInterruptionListener inInterruptionListener = NULL;
OSStatus error;
if ((error = AudioSessionInitialize (NULL, NULL, inInterruptionListener, NULL)))
NSLog(@"*** Error *** error in AudioSessionInitialize: %d.", error);
else
gAudioSessionInited = YES;
}
SInt32 ambient = kAudioSessionCategory_AmbientSound;
if (AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (ambient), &ambient))
{
NSLog(@"*** Error *** could not set Session property to ambient.");
}
关于iphone - 在 iOS 5 中检测 iPhone 静音开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8158087/