AVAudioPlayer不能同时播放声音

我正在尝试为AVAudioPlayer同时播放几个声音文件。 我读了一个解释如何做的线程@ AVAudioPlayer Help:同时播放多个声音,一次停止所有声音,并解决自动引用计数问题 。 这似乎是一个奇怪的问题,当我试图一次只播放一个文件(当self.options.on是ON),它的工作原理,但是当我尝试创build多个实例(else语句),并播放他们什么都没有播放。 我检查,看是否输出文件的URL是正确的,那是什么原因,它不工作?

谢谢!

- (void)playTapped:(id)sender { if (!recorder.recording) { if(self.options.on) { AVAudioSession *session = [AVAudioSession sharedInstance]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], [NSString stringWithFormat:@"sound%i.m4a",last], nil]; NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents]; player = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil]; NSLog(@"%@",player.url); [player setDelegate:self]; [player play]; } else { // trying to play all sounds at once for (NSString *str in self.soundsCreated){ NSLog(@"%@",str); NSArray *pathComponents = [NSArray arrayWithObjects: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], [NSString stringWithFormat:@"sound%@.m4a",str], nil]; NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents]; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil]; NSLog(@"%@",audioPlayer.url); [audioPlayer prepareToPlay]; [audioPlayer setDelegate:self]; [audioPlayer play]; } } } } 

注意我尝试初始化与NSError检查,但我没有得到任何错误:

 NSError *sessionError = nil; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:&sessionError]; if (sessionError) { NSLog(@"Error in audioPlayer: %@",[sessionError localizedDescription]); } 

解决scheme这似乎是我的NSMutableArray的初始化问题。

我改变了他们:

 self.soundsCreated = [[NSMutableArray alloc]init]; self.playerArray = [[NSMutableArray alloc]init]; 

 self.soundsCreated = [NSMutableArray new]; self.playerArray = [NSMutableArray new]; 

并修复它

我面对同样的一个小文件:

这是我的解决scheme(示例)

 - (void)dropSoundWhileRefresh { NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError]; [[AVAudioSession sharedInstance] setActive:YES error:&sessionError]; [[AVAudioSession sharedInstance] setDelegate:self]; NSURL *musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"waterDrops" ofType:@"mp3"]]; dropSound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil]; [dropSound setDelegate:self]; [dropSound setVolume:0.10]; [dropSound setNumberOfLoops:0]; [dropSound play]; } 

而不是通过错误作为零试试这个,并检查是否初始化工作正确。

 AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; if (error) { DebugLog(@"Error in audioPlayer: %@",[error localizedDescription]); }