How does audioPlayerDidFinishPlaying know which file is finished?

我的梦境 提交于 2020-01-03 00:54:48

问题


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 ([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");
} 

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.


回答1:


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


来源:https://stackoverflow.com/questions/5343084/how-does-audioplayerdidfinishplaying-know-which-file-is-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!