如何在显示视图之前阻止AVAudioPlayer播放

时间:2011-09-14 07:04:52

标签: iphone objective-c uinavigationcontroller avaudioplayer

您好我有一个名为HomeViewController的UIView,它使用UINavigationController。只需单击一个按钮,我就可以使用以下代码推送另一个视图:

gameView = [[GameViewControler alloc] init];
    [[self navigationController] pushViewController:gameView animated:YES];
    [gameView release];

在GameViewController的viewDidLoad中,我使用以下代码依次播放两个音频文件:

//处理声音的东西

if([[GameStore defaultStore] currentIndex] == 0)
{
    if(![audioPlayer isPlaying])
    {
        NSString *findPath = [[NSBundle mainBundle] pathForResource:@"findtheword" ofType:@"aiff"];
        if(findPath)
        {
            NSURL *findURL = [NSURL fileURLWithPath:findPath];
            NSError *findError;
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:findURL error:&findError];

            if(audioPlayer == nil)
            {
                NSLog([findError description]);
            }
            else{
                [audioPlayer play];
            }
        }
    }
}

while ([audioPlayer isPlaying]) {
    //do nothing and wait so the sound is not overlap
}


if(![audioPlayer isPlaying] || ([audioPlayer isPlaying] && override)){
    Word *currentWord = [[GameStore defaultStore] currentWord];
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:[currentWord fileName]
                                                      ofType:[currentWord fileType]];
    // If this file is actually in the bundle...
    if (soundPath) {
        // Create a file URL with this path
        NSURL *soundURL = [NSURL fileURLWithPath:soundPath];

        NSError *error;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];

        if (audioPlayer == nil)
            NSLog([error description]);
        else
            [audioPlayer play];
    }
    [FlurryAnalytics logEvent:@"GameViewController - playSound"];
}
else{
    [FlurryAnalytics logEvent:@"GameViewController - playSound is still playing"];
}

我无法弄清楚为什么第一个音频文件开始播放,而屏幕仍在HomeViewController上,即使它是从GameViewController的viewDidLoad调用的。

如果我删除以下代码:

while ([audioPlayer isPlaying]) {
    //do nothing and wait so the sound is not overlap
}

加载GameViewController但第二个音频文件重叠时,第一个音频文件开始播放。

非常感谢。

2 个答案:

答案 0 :(得分:1)

单击HomeViewController中的某个按钮或表格视图单元格后,音频文件是否开始播放?同样,它会在GameViewController的视图从右到左动画时开始播放?如果是这样,那么因为在实际呈现视图之前调用了-viewDidLoad。您需要做的是将视图逻辑放在-viewDidAppear:中。只有在视图完成动画并且完全可见时才会调用它。

答案 1 :(得分:1)

您可以将代码从viewDidLoad移至viewDidAppear: