iPhone:AVAudioPlayer并不总是在设备上播放音频

时间:2011-03-13 12:51:53

标签: iphone objective-c avaudioplayer

我的应用程序中有2个视图,它们是相同的,它们只是加载不同的声音文件数组,以便与各自的AVAudioPlayer一起使用。 但是,仅在设备上,在我的第二个视图中,声音似乎只在初始化后播放一次,然后在我再次初始化播放器之前它不播放。

这是我的播放按钮代码:

- (IBAction)play:(id)sender {
if (((int)buttonCount % 2) == 0) {
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    self.audioPlayer.currentTime = 0;
    self.audioPlayer.volume = volumeSlider.value;
    [self.audioPlayer play];
    [playButton setTitle:@"Stop..." forState:UIControlStateNormal];
    buttonCount++;
    [self fadePickerAnimation:NO];
    NSLog(@"Should play");
}
else {
    [self initializeSoundAfterStop:YES];
    NSLog(@"Shouldn't play");
}
NSLog(@"buttoncount %i",buttonCount);
NSLog(@"What is the playing state? %i", self.audioPlayer.playing);

}

以及它在else子句下调用的函数:

- (void)initializeSoundAfterStop:(BOOL)addToButtonCount {
//Initialize audioPlayer once completely stopped
[self.audioPlayer stop];
[self.audioPlayer prepareToPlay];
[playButton setTitle:@"Chime!" forState:UIControlStateNormal];
if (addToButtonCount == YES) {
    buttonCount++;
}}

上面代码中的NSLog输出了这个,因为我连续按下播放按钮:

Should play
buttoncount 1
What is the playing state? 1
Shouldn't play
buttoncount 2
What is the playing state? 0
Should play
buttoncount 3
What is the playing state? 0
Shouldn't play
buttoncount 4
What is the playing state? 0
Should play
buttoncount 5
What is the playing state? 0
Shouldn't play
buttoncount 6
What is the playing state? 0

正如您所看到的,由于某种原因,它会陷入非播放模式。 在我的第一个视图中,此方法以完全相同的方式使用,并且它没有任何问题。这一切在模拟器上运行良好,而不是在我的iPhone 4上。无法解决这个问题。当我设置断点时,会调用audioPlayer的播放方法,所以我不知道! 谢谢!

1 个答案:

答案 0 :(得分:2)

无法找出发生这种情况的原因,但是,我通过在播放IBAction的顶部添加我的AVAdioPlayer初始化函数来修复它。 可能不是最优雅的解决方案,但它确实有效。

如果您决定这样做,请注意内存分配。