开发者

How does audioPlayerDidFinishPlaying know which file is finished?

开发者 https://www.devze.com 2023-02-18 00:15 出处:网络
I am using AVAudioPlayer to play a 15 audio files.The audio files need to be played in sets of 5 with each set having three files.The three files within a set do not change.The order that the sets are

I am using AVAudioPlayer to play a 15 audio files. The audio files need to be played in sets of 5 with each set having three files. The three files within a set do not change. The order that the sets are played may change.

I tried using a while loop with isPlaying like this:

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 ([backgroundSo开发者_运维百科und 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");
} 

I now realize that this is wrong with the side effect being that the entire UI is locked up for the duration of the file being played.

I know I should be using:

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

But I do not know how audioPlayerDidFinishPlaying is supposed to know exactly which file has finished playing.

I thought it might be like - (void)animationDidStop where you can use a valueForKeyPath to figure out which file was finished playing.

Does it have to be tracked manually?

Any suggestions to point me in the right direction would be appreciated.

Thank you.


When an AVAudioPlayer calls the audioPlayerDidFinishPlaying method, it supplies itself as an argument. So what you should do is check the URL to figure out which file just finished playing.

-(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
     }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消