简体   繁体   中英

iPhone: AVAudioPlayer not always playing audio on device

I have 2 views in my app, that are identical, they just load in a different array of sound files to use with their respective AVAudioPlayer. However, ON THE DEVICE ONLY, on my second view, the sound seems to only play once after initialization, then it doesn't play until I initialize the player again.

This is my play button code:

- (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);

}

and the function it calls under the else clause:

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

The NSLogs in the above code output this as I continuously press the play button:

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

So as you can see, it gets stuck in a non-playing mode for some reason. This method is used in exactly the same fashion in my first view, and it works without any problem. And it all works fine on the simulator, just not on my iPhone 4. Cannot figure this out. The play method of audioPlayer gets called when I setup a breakpoint, so I dunno! Thanks!

Couldn't find out why this was happening, however, I fixed it by simply adding in my AVAdioPlayer initializer function at the top of the play IBAction. Might not be the most graceful solution, but it works.

Just beware of memory allocation if you decide to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM