我正在尝试为 iPhone 应用程序输出设置音频路由。我正在使用路由更改侦听器来检测音频路由何时更改。侦听器会检测到变化,例如插入和拔出耳机的时间。默认情况下,扬声器播放音频,然后我插入耳机,音频通过耳机正常传输。从那里开始,任何更改都不会发生,即使路由更改侦听器正在检测它们。
任何帮助将非常感激。
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
error:&sessionError];
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory),
&sessionCategory);
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof(sessionCategory), &sessionCategory);
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange,
RouteChangeListener, (__bridge void *)(self));
AudioSessionSetActive(YES);
回调监听器:
void RouteChangeListener(
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
const void *inPropertyValue)
{
if (inPropertyID == kAudioSessionProperty_AudioRouteChange) {
CFStringRef newRoute;
UInt32 size = sizeof(CFStringRef);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &newRoute);
if (newRoute) {
CFShow(newRoute);
if (CFStringCompare(newRoute, CFSTR("SpeakerAndMicrophone"),
(UInt32)NULL) == kCFCompareEqualTo) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof(audioRouteOverride), &audioRouteOverride);
} else if (CFStringCompare(newRoute, CFSTR("HeadphonesAndMicrophone"),
(UInt32)NULL) == kCFCompareEqualTo) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
sizeof(audioRouteOverride), &audioRouteOverride);
[[[AVAudioSession sharedInstance] player] play];
}
}
}
}