iphone - AVAudioPlayer 帮助 : Playing multiple sounds simultaneously, 一次停止它们,并解决自动引用计数

标签 iphone objective-c ios audio avaudioplayer

我正在尝试创建播放单个声音文件的按钮和一个停止当前正在播放的所有声音的按钮。如果用户在短时间内点击多个按钮或同一个按钮,应用程序应该同时播放所有声音。我使用 iOS 的系统声音服务毫不费力地完成了这项工作。但是,系统声音服务通过 iPhone 的 铃声设置的音量 播放声音。我现在正在尝试使用 AVAudioPlayer 以便用户可以通过媒体音量播放 声音。这是我目前(但未成功)使用播放声音的代码:

-(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 上运行它时,根本就没有声音。经过一些研究和测试,我发现 audioPlayer 变量正在被自动引用计数释放。此外,当 audioPlayer 变量被定义为我的接口(interface)文件中的实例变量和属性时,此代码有效,但它不允许我一次播放多个声音。

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

最佳答案

首先,将 audioplayer 的声明和分配/初始化放在同一行。此外,每个 AVAudioPlayer 只能播放一种声音,但您可以同时播放任意数量的声音。然后要停止所有声音,可以使用 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];
  }

这应该可以满足您的需求。

关于iphone - AVAudioPlayer 帮助 : Playing multiple sounds simultaneously, 一次停止它们,并解决自动引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11194838/

相关文章:

ios - FaSTLane:将设备添加到配置的正确方法?

ios - 如何查找UIwebview是否正在使用缓存加载IOS中的数据

iphone - 检测是否在 Cocos2d-iphone 上触摸了特定的 Sprite

iphone - 从 Content-Disposition header 获取文件名

iphone - 应用内购买 (IAP) 简单问题(我有问题)

objective-c - NSAttributedString kCTParagraphStyleSpecifierParagraphSpacing 无效

objective-c - 有没有办法将 Protocol Buffer 包装到 Objective-C 中并仍然利用继承?

objective-c - 将 NSString 中每个句子的首字母大写

ios - 尝试实现从 MVC 的模型部分到 View Controller 的方法

ios - JSON 框架解析错误