【发布时间】:2011-09-05 10:32:38
【问题描述】:
我必须创建一个应用程序,让 iPhone 在按下按钮事件时静音。
如何以编程方式做到这一点?
【问题讨论】:
标签: iphone ios ipad cocoa-touch user-experience
我必须创建一个应用程序,让 iPhone 在按下按钮事件时静音。
如何以编程方式做到这一点?
【问题讨论】:
标签: iphone ios ipad cocoa-touch user-experience
官方 iOS SDK 中没有任何内容可以执行此操作。想象一下,有人错过了一个重要的电话,因为应用程序在用户不知情的情况下更改了设置并使手机静音。我不想肯定下载那个应用程序。请参阅this 相关问题。
来自 Apple 的文档
应该由人而不是应用程序发起和控制操作。 尽管应用程序可以建议采取行动或警告 危险的后果,这通常是应用程序采取的错误 远离用户的决策。最好的应用程序找到正确的 在为人们提供所需能力的同时提供帮助之间取得平衡 他们避免了危险的结果。
如果我没记错的话,让手机静音就是这样一种行为。
阅读苹果documentation的声音部分。
前往苹果开发者论坛(您必须登录),并查看this 线程。在那里接电话的人是一位苹果员工。
【讨论】:
// "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.");
}
希望对您有所帮助...
【讨论】:
-(BOOL)muteSwitchEnabled {
#if TARGET_IPHONE_SIMULATOR
// set to NO in simulator. Code causes crashes for some reason.
return NO;
#endif
// go back to Ambient to detect the switch
AVAudioSession* sharedSession = [AVAudioSession sharedInstance];
[sharedSession setCategory:AVAudioSessionCategoryAmbient error:nil];
CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
BOOL muteSwitch = (CFStringGetLength(state) <= 0);
NSLog(@"Mute switch: %d",muteSwitch);
// code below here is just restoring my own audio state, YMMV
_hasMicrophone = [sharedSession inputIsAvailable];
NSError* setCategoryError = nil;
if (_hasMicrophone) {
[sharedSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &setCategoryError];
// By default PlayAndRecord plays out over the internal speaker. We want the external speakers, thanks.
UInt32 ASRoute = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof (ASRoute),
&ASRoute
);
}
else
// Devices with no mike don't support PlayAndRecord - we don't get playback, so use just playback as we don't have a microphone anyway
[sharedSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(@"Error setting audio category! %@", setCategoryError);
return muteSwitch;
}
先切换到环境,读取开关,然后返回设置...
【讨论】:
没有对开发人员开放的公共 api,因为当您的应用程序正在运行并且您接到电话时,您的应用程序将退出或可能处于后台但您无法对设备进行任何更改。因为也会进行呼叫关于系统级事件
【讨论】: