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

bna*_*sty 4 iphone audio objective-c avaudioplayer ios

我想创建一个按钮,play一个声音文件,一个buttonstops所有的声音当前正在播放.如果用户button在短时间内单击多个按钮或相同按钮,应用程序应同时播放所有声音.我使用iOS的System Sound Services毫不费力地完成了这项工作.但是,系统声音服务,通过播放声音volumeiPhone's铃声设置为.我现在正在尝试使用,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];
}
Run Code Online (Sandbox Code Playgroud)

每当我在iPhone模拟器中运行此代码时,它都不会播放声音,但会显示大量输出.当我在iPhone上运行时,声音根本无法播放.在做了一些研究和测试之后,我发现audioPlayer变量是由自动参考计数发布的.此外,当audioPlayer变量被定义为我的接口文件中的实例变量和属性时,此代码可以工作,但它不允许我一次播放多个声音.

首先是第一件事:如何使用AVAudioPlayer和坚持使用自动参考计数一次播放无限数量的声音?另外:当这些声音播放时,我如何实现第二种IBAction方法来停止播放所有这些声音?

Dus*_*tin 16

首先,将声明和alloc/init audioplayer放在同一行.此外,你只能每声播放一首声音,AVAudioPlayer你可以同时制作任意数量的声音.然后停止所有的声音,也许使用a 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];
  }
Run Code Online (Sandbox Code Playgroud)

那应该做你需要的.

  • 为了避免泄漏要设置audioPlayer的和在下面的委托方法委托删除从阵列的参考: - (无效)audioPlayerDidFinishPlaying:(AVAudioPlayer*)玩家成功:(BOOL)标志{[self.soundsArray的removeObject:播放器] } (3认同)