问题描述
|
我目前正在使用一段代码来检测用户是否已将iPhone插入/拔出耳机。我用来检测它的方法如下所示。
void audioRouteChangeListenerCallback (void *inUserData,AudioSessionPropertyID inPropertyID,UInt32 inPropertyValueSize,const void *inPropertyValue){
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
CFStringRef route; UInt32 routeSize = sizeof(CFStringRef);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute,&routeSize,&route);
NSString *oldroute = (NSString*)route;
NSLog(@\"Audio Route changed to: %@\",oldroute);
}
我要拔掉耳机时出现问题。插入它们可以按预期工作,日志文件显示\“音频路径更改为:耳机\”,但是,当我拔出插头时,会得到一个用于oldroute的空字符串。我希望这个值将是\“ Speaker \”,就像苹果文件中所说的那样。有没有人见过这个?在获取字符串oldroute时我做错什么了吗?谢谢
解决方法
对于我作为问题发布的确切问题,我仍然没有找到好的答案。这是一个变通办法,可能对有些类似问题的人有用。该解决方案为您提供了更改前处于活动状态的路由。例如如果拔下耳机,您将得到一个字符串“ \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\“扬声器\\\\\\\\\\”,\\“扬声器\\\”。
void audioRouteChangeListenerCallback (void *inUserData,AudioSessionPropertyID inPropertyID,UInt32 inPropertyValueSize,const void *inPropertyValue){
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
CFDictionaryRef routeChangeDictionary = (CFDictionaryRef)inPropertyValue;
CFStringRef oroute;
oroute = (CFStringRef)CFDictionaryGetValue(routeChangeDictionary,CFSTR(kAudioSession_AudioRouteChangeKey_OldRoute));
NSString *oldroute = (NSString*)oroute;
}
希望这可以帮助。
编辑:我将接受我的答案,直到出现更好的答案
, 我目前使用以下内容:
void _propertyListener( void * inClientData,AudioSessionPropertyID inID,UInt32 inDataSize,const void * inData) {
if (inID != kAudioSessionProperty_AudioRouteChange) {
return;
}
dispatch_async(dispatch_get_main_queue(),^{
[[NSNotificationCenter defaultCenter] postNotificationName:kAudioRouteChanged object:nil];
});
}
- (void) _audioRouteChanged:(NSNotification*)notification
{
NSLog(@\"audioRouteChanged\");
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,&routeSize,&route);
/* Known values of route:
* \"Headset\"
* \"Headphone\"
* \"Speaker\"
* \"SpeakerAndMicrophone\"
* \"HeadphonesAndMicrophone\"
* \"HeadsetInOut\"
* \"ReceiverAndMicrophone\"
* \"Lineout\"
*/
if (!error && (route != NULL)) {
NSString* routeStr = (__bridge NSString*)route;
NSRange headphoneRange = [routeStr rangeOfString : @\"Head\"];
[self.cardSwipeDelegate headphoneListener:(headphoneRange.location != NSNotFound)];
if (headphoneRange.location != NSNotFound) {
[self startSession];
} else {
[self stopSession];
}
}
}
在您进行初始化的任何地方添加通知:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(_audioRouteChanged:) name:kAudioRouteChanged object:nil];