了解耳机何时连接到 3.5 毫米插孔仅在应用程序启动前未连接时才有效



我得到了这个代码来判断耳机是否连接:

This in 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函数不调用时,耳机已经连接在应用程序开始之前?

您需要在应用程序加载/启动时提供检查。基本上你应该能够调用:

- (void) viewDidLoad
{
    isHeadsetPluggedIn()
}

如果在连接耳机之前没有启动应用程序,则未设置属性监听器。请注意,属性侦听器只检查更改。

因此,您需要在应用程序加载/启动时提供检查。您可以直接获得AudioSession属性,而无需使用侦听器,从而进行解析。这就是你在isHeadsetPluggedIn()中所做的你调用:

OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                      &routeSize,
                                      &route);  

这个方法可以在objective c和c++函数中调用。在初始化AudioSession后,可以在任何地方调用它来获取AudioSession的任何属性。

相关内容

  • 没有找到相关文章

最新更新