Joel Ferman
Joel Ferman

Reputation: 51

How to tell that AVAudioPlayer has finished playing

I'm developing an app that plays sounds using AVAudioPlayer, and I want to know when a sound has finished playing. I want to change an image when the sound stops playing

Here's the code I use to create the player:

NSURL* url = [[NSBundle mainBundle] URLForResource:@"LOLManFace1"  withExtension:@"mp3"];
NSAssert(url, @"URL is valid.");
NSError* error = nil;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&url];error;

if(!self.player)
{
    NSLog(@"Error creating player: %@", error);
}

And here's the code I use to play the sound:

[self.player play];

How can I tell that playback has finished?

Thank you so much in advance!

Upvotes: 5

Views: 8486

Answers (2)

nice_pink
nice_pink

Reputation: 523

Long time ago and I am pretty sure you figured out at one point. If someone reads this post:

1) Your class should implement the AVAudioPlayerDelegate. (https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate)

One of the delegate methods is:

audioPlayerDidFinishPlaying:successfully:

2) Set delegate:

self.player.delegate = self

Upvotes: 3

Daniel
Daniel

Reputation: 22395

Look at the AVAudioPlayerDelegate protocol which has a method to tell the delegate when audio playback has finished among other things, specifically what you are looking for is - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag, here is a reference

Hope it helps

Daniel

Upvotes: 10

Related Questions