1
votes

I am using AVAudioPlayer class to play audio but the problem is that when I play the audio I do not receive the callback in audioPlayerDidFinishPlaying when the file is finish playing and the file starts again even when the number of loops is set to 1

Here is the code.

.h

@interface AudioController : NSObject <AVAudioPlayerDelegate>

-(void) playBigGameTheme{
-(void) playMusic:(NSString*) fileName isLooping: (BOOL) isLooping;
@end

.m

@implementation AudioController{

    AVAudioPlayer *audioPlayer;
}

-(void) playMusic:(NSString*) fileName isLooping: (BOOL) isLooping{

    int loop = 1;
    if(isLooping){
        loop = -1;
    }

    [audioPlayer stop];
    NSURL* soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName  ofType:@"mp3"]];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
    audioPlayer.numberOfLoops = loop;
    [audioPlayer setDelegate:self];
    NSLog(@"===Number of loops : %d", audioPlayer.numberOfLoops);    
    [audioPlayer play];
}

- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"HERE");
}

-(void) playBigGameTheme{
    [self playMusic:BGAME_MAIN_MUSIC_FILE_NAME isLooping:NO];
}
@end

when I call playBigGameTheme the audio starts playing correctly. but it restarts when the sound is finished and when the audio finishes the second time then only the audioPlayerDidFinishPlaying method is called.

I am stuck and do not know whats going wrong..

1

1 Answers

3
votes

even when the number of loops is set to 1

That's exactly why. The name and the behavior of this property is a bit counter-intuitive, but if you had read the documentation, it would have been clear that it sets the number of repetitions, and not the number of playbacks. Quote from the docs:

The value of 0, which is the default, means to play the sound once.

So set it to 0 (or don't set it, zero is the default value) and it will play the audio file only once:

audioPlayer.numberOfLoops = 0;