Goe*_*her 9 multithreading uiview mpmusicplayercontroller ios avaudiosession
在我的iOS应用程序中,我正在尝试实现"躲避":当我的应用程序播放一个简短的"命令式"声音时,任何背景音乐都应该降低音量.完成播放声音后,音乐音量应恢复到原始值.
实施后,避免基本上按预期工作.但是,当我在audioPlayerDidFinishPlaying中调用AudioSessionSetActive(NO)时:为了结束闪避,此时发生的任何UI更新都会暂停一小段时间.这包括自定义绘图,以及前者.自动滚动文本等.
现在,问题是:
这是iOS6中的已知问题吗?我在iPod/iOS5上运行相同的代码,我没有看到这种行为.或者我错过了代码中的某些内容?也许你们其中一个人已经遇到同样的问题并找到了可行的解决方案.
非常感谢您的支持,
戈茨
- (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);
}
Run Code Online (Sandbox Code Playgroud)
经过一番摸索和调试,我找到了这个问题的答案。正如原始问题所述,为了在闪避后恢复音频电平,您必须停用音频会话。
问题在于,在播放音频时停用会话会导致 0.5 秒延迟,这会阻塞 UI 线程并导致应用程序无响应(在我的情况下,计时器丢失 0.5 秒并断断续续)。
为了解决这个问题,我打电话在一个单独的线程上停用计时器。这解决了 UI 阻塞问题并允许音频按预期闪避。下面的代码显示了解决方案。请注意,这是 C# 代码,因为我使用的是 Xamarin,但它可以轻松转换为 Objective-C 或 Swift 以获得相同的结果:
private void ActivateAudioSession()
{
var session = AVAudioSession.SharedInstance();
session.SetCategory(AVAudioSessionCategory.Playback, AVAudioSessionCategoryOptions.DuckOthers);
session.SetActive(true);
}
private void DeactivateAudioSession()
{
new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
var session = AVAudioSession.SharedInstance();
session.SetActive(false);
})).Start();
}
Run Code Online (Sandbox Code Playgroud)
我在连接 AVAudioPlayer 之前调用 ActivateAudioSession,一旦我的播放器播放完毕,我就调用 DeactivateAudioSession(这是恢复音频电平所必需的)。在新线程上启动停用会降低音频级别,但不会阻塞 UI。