我得到这段代码来判断耳机是否已连接:
这在viewDidLoad:
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioSessionPropertyListener, nil);
此功能:
void audioSessionPropertyListener(void* inClientData, AudioSessionPropertyID inID,
UInt32 inDataSize, const void* inData) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
// Determines the reason for the route change, to ensure that it is not
// because of a category change.
CFDictionaryRef routeChangeDictionary = inData;
CFNumberRef routeChangeReasonRef = CFDictionaryGetValue (routeChangeDictionary,CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
// "Old device unavailable" indicates that a headset was unplugged, or that the
// device was removed from a dock connector that supports audio output.
if (routeChangeReason != kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[[Cubic_01AppDelegate sharedInstance] setDongleIsDisonnected];
}
if (!isHeadsetPluggedIn())
{
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
}
}
和这个功能:
BOOL isHeadsetPluggedIn() {
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route
);
NSLog(@"%@", route);
BOOL isPluggedIn = !error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound);
if (isPluggedIn) {
[[Cubic_01AppDelegate sharedInstance] setDongleIsConnected];
} else {
[[Cubic_01AppDelegate sharedInstance] setDongleIsDisonnected];
}
return (isPluggedIn);
}
任何人都可以帮忙告诉我为什么在应用程序启动之前耳机已经连接时没有调用audioSessionPropertyListener函数?
答案 0 :(得分:0)
您需要提供有关应用程序加载/启动的检查。基本上你应该可以打电话:
- (void) viewDidLoad
{
isHeadsetPluggedIn()
}
如果在连接耳机之前尚未启动应用程序,则尚未设置属性侦听器。请注意,属性侦听器仅检查更改。
因此,您需要提供有关应用程序加载/启动的检查。您可以直接获取AudioSession属性,而无需使用侦听器进行解析。这正是你在isHeadsetPluggedIn()中所做的事情:你打电话:
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route);
此方法可以在目标c和c ++函数中调用。在初始化后,可以在任何地方调用它以获取AudioSession的任何属性。