尝试修复 AVAudioPlayer 在其初始使用时的滞后 [英] Trying to fix AVAudioPlayer lag on its initial use
问题描述
此问题已出现在 SO 上的其他几个问题中:
This issue has shown up in several other question here on SO:
我已尝试实施建议的修复,但没有一个解决我的问题.我的应用程序向用户展示了要触摸的对象网格,当触摸对象时会播放声音.这很好用,只是在初次触摸时会有约 2 秒的延迟.
I've tried implementing the fixes suggested but none of them are solving my problem. My application presents the user with a grid of objects to touch, when an object is touched a sound is played. This works great except on the initial touch there is a delay of ~2 seconds.
为了解决这个问题,我用一个虚拟的 aiff 文件初始化我的音频播放器:
To get around this I initialize my audio player with a dummy aiff file:
- (void)viewDidLoad{
NSString *soundFile = [Card loadCardSoundPath:@"dummy"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:soundFile] error:nil];
self.audioPlayer = player;
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
// [audioPlayer play];
[player release];
...
[super viewDidLoad];
}
然后当一个物体被触摸时,我会调用:
Then when an object is touched I call:
NSString *soundFile = [Card loadCardSoundPath:name];
if (soundFile != nil){
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:soundFile] error:nil];
self.audioPlayer = player;
[self.audioPlayer setDelegate:self];
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
[player release];
}
我观察到的行为是这样的:如果我创建一个虚拟音频播放器并调用 prepareToPlay 但不播放,我会在单击第一个对象时观察到音频延迟.但是,如果我在虚拟音频播放器上调用 play,那么我不会得到初始对象的延迟,但视图加载会延迟 2 秒.
The behavior i'm observing is this: I observe the audio delay when I click the first object if I create a dummy audio player and call prepareToPlay but not play. However if I call play on the dummy audio player then I don't get the delay on the initial object but the view load gets delayed by 2 seconds.
有没有办法解决这个问题?我是否应该在加载时简单地创建一个 AVAudioPlayers 的 NSArray 并告诉他们准备播放,然后在单击对象时调用 play?
Is there a way to get around this? Should I simply create an NSArray of AVAudioPlayers on load and tell them all to prepare to play, and then just call play when the object is clicked?
推荐答案
有时通过使用 peformSelector:withObject:afterDelay:
代码>.例如:
Sometimes it can help to let viewDidLoad
return by spooling off initialization like that using peformSelector:withObject:afterDelay:
. For example:
- (void)viewDidLoad{
// initialization ...
[super viewDidLoad];
[self performSelector:@selector(primeAudioPlayer) withObject:nil afterDelay:0.1];
}
-(void)primeAudioPlayer {
NSString *soundFile = [Card loadCardSoundPath:@"dummy"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:soundFile] error:nil];
[audioPlayer prepareToPlay];
[player release];
}
这篇关于尝试修复 AVAudioPlayer 在其初始使用时的滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!