在我的iOS应用程序中,我正在尝试实现“ ducking”: 当我的应用程序播放短暂的“命令式”声音时,任何背景音乐都应该降低音量。播放完毕后,音乐音量应恢复到其原始值。目前为止,ducking基本上按预期工作。然而,在audioPlayerDidFinishPlaying:中调用AudioSessionSetActive(NO)以结束ducking时,此时发生任何UI更新都会有一个小的暂停。包括自定义绘制,以及例如文本的自动滚动等内容。现在问题来了:这是iOS6中已知的问题吗?我在iPod / iOS5上运行相同的代码,那里没有看到这种行为。还是我从代码中漏掉了什么?也许你们中的一些人已经遇到过同样的问题并找到了可行的解决方案。非常感谢您的支持,Goetz
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//...
NSError *err = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&err];
//...
}
- (void) playSound {
// Enable ducking of music playing in the background (code taken from the Breadcrumb iOS Sample)
UInt32 value = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(value), &value);
// Required if using kAudioSessionCategory_MediaPlayback
value = YES;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(value), &value);
UInt32 isOtherAudioPlaying = 0;
UInt32 size = sizeof(isOtherAudioPlaying);
AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &size, &isOtherAudioPlaying);
if (isOtherAudioPlaying) {
AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(value), &value);
}
AudioSessionSetActive(YES);
// Initialization of the AVAudioPlayer
NSString *soundFileName = [[NSBundle mainBundle] pathForResource:@"Beep" ofType:@"caf"];
NSURL *soundFileURL = [[NSURL alloc] initFileURLWithPath:soundFileURL];
self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
[self.soundPlayer setDelegate:self];
[self.soundPlayer setVolume:[80.0/100.0];
[self.soundPlayer play];
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
// Callback coming from the AVAudioPlayer
// This will block the main thread; however, it is necessary to disable ducking again
AudioSessionSetActive(NO);
}