AVAudioPlayer帮助:同时播放多个声音,一次停止所有声音,以及解决自动参考计数问题

我正在尝试创buildplay单个声音文件的button和一个stops所有正在播放的声音的button 。 如果用户在短时间内点击多个button或同一个button ,应用程序应该同时播放所有的声音。 使用iOS的系统声音服务,我已经完成了这个工作。 但是,System Sound Services会通过iPhone's铃声设置的volume播放声音。 我正在尝试使用AVAudioPlayer以便用户可以通过媒体音量play声音。 这是我目前(但不成功)使用播放声音的代码:

 -(IBAction)playSound:(id)sender { AVAudioPlayer *audioPlayer; NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Hello" ofType:@"wav"]; audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil]; [audioPlayer prepareToPlay]; [audioPlayer play]; } 

每当我在iPhone模拟器中运行这个代码,它不会播放声音,但会显示大量的输出。 当我在iPhone上运行它时,声音根本不起作用。 在做了一些研究和testing之后,我发现audioPlayervariables正在被自动引用计数发布。 另外,当audioPlayervariables被定义为一个实例variables和接口文件中的一个属性时,这个代码就可以工作,但是它不允许我一次播放多个声音。

首先是:如何使用AVAudioPlayer一次播放无限的声音并坚持自动引用计数? 另外:当这些声音正在播放,我怎么能实现第二个IBAction方法来停止播放所有这些?

首先,把audioplayer的声明和alloc / init放在同一行。 另外,每个AVAudioPlayer只能播放一个声音,但是你可以同时创build多个声音。 然后停止所有的声音,也许使用一个NSMutableArray ,添加所有的球员,然后迭代, [audioplayer stop];

 //Add this to the top of your file NSMutableArray *soundsArray; //Add this to viewDidLoad soundsArray = [NSMutableArray new] //Add this to your stop method for (AVAudioPlayer *a in soundsArray) [a stop]; //Modified playSound method -(IBAction)playSound:(id)sender { NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"Hello" ofType:@"wav"]; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundFile] error:nil]; [soundsArray addObject:audioPlayer]; [audioPlayer prepareToPlay]; [audioPlayer play]; } 

这应该做你所需要的。