试图修复AVAudioPlayer在初次使用时滞后

时间:2011-04-16 04:01:36

标签: ios4 avaudioplayer delay lag

此问题已在SO上显示在其他几个问题中:

Slow start for AVAudioPlayer the first time a sound is played

Delay in playing sounds using AVAudioPlayer

我尝试过实施修正建议,但没有一个能解决我的问题。我的应用程序向用户呈现要触摸的对象网格,当触摸对象时播放声音。这很有效,除了在初始触摸时有延迟~2秒。

为了解决这个问题,我用虚拟的aiff文件初始化我的音频播放器:

- (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]; 
}

然后当触摸一个物体时,我打电话给:

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但没有播放时,我会在单击第一个对象时观察音频延迟。但是,如果我在虚拟音频播放器上调用播放,那么我不会在初始对象上获得延迟,但视图加载会延迟2秒。

有没有办法解决这个问题?我是否应该在加载时简单地创建一个AVAudioPlayers的NSArray并告诉他们所有人准备播放,然后在单击该对象时调用play?

1 个答案:

答案 0 :(得分:4)

有时通过假设使用viewDidLoad进行初始化来让peformSelector:withObject:afterDelay:返回是有帮助的。例如:

- (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];
}