How does audioPlayerDidFinishPlaying know which file is finished?

I am using AVAudioPlayer to play 15 audio files. Audio files must be played in sets of 5 with each set having three files. The three files within the set are not modified. The order in which sets are played may change.

I tried using a while loop with isPlaying as follows:

while ([backgroundSound isPlaying]) { NSLog(@"First while loop"); } backgroundSoundPath = [[NSBundle mainBundle] pathForResource:@"Set0File1" ofType:@"mp3"]; // *Music filename* backgroundSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:backgroundSoundPath] error:nil]; [backgroundSound prepareToPlay]; [backgroundSound play]; while ([backgroundSound isPlaying]) { NSLog(@"Second while loop"); } backgroundSoundPath = [[NSBundle mainBundle] pathForResource:@"Set0File2" ofType:@"mp3"]; // *Music filename* backgroundSound =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:backgroundSoundPath] error:nil]; [backgroundSound prepareToPlay]; [backgroundSound play]; while ([backgroundSound isPlaying]) { NSLog(@"Third while loop"); } 

Now I understand that this is wrong with the side effect that the entire user interface is locked while the file is playing.

I know I have to use:

  • (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successful: (BOOL) flag

But I don’t know how audioPlayerDidFinishPlaying should sound exactly which file has finished playing.

I thought it could be like (void) animationDidStop, where you can use valueForKeyPath to figure out which file was finished.

Do I need to track it manually?

Any suggestions pointing me in the right direction would be appreciated.

Thanks.

+1
source share
1 answer

When AVAudioPlayer calls the audioPlayerDidFinishPlaying method, it exposes itself as an argument. So what you need to do is check the url to find out which file just finished.

 -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { if ([player.url isEqual:url1]) { // file which is in url1 stopped playing } else if ([player.url isEqual:url2]) { // file which is in url2 stopped playing } } 
+8
source

Source: https://habr.com/ru/post/921646/


All Articles