iphone - AVAudioPlayer 不加载声音

标签 iphone objective-c ios ipad avfoundation

无论出于何种原因,我在使用 AVAudioPlayer 加载声音时遇到了问题。我正在我的 iPad 设备上测试它。

我的代码相当简单,没有什么花哨的。框架已导入,委托(delegate)已实现。在我的 viewDidLoad 方法中:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc]
                           initWithContentsOfURL:[NSURL fileURLWithPath:path]
                                           error:NULL];
[theAudio setDelegate:self];
[theAudio prepareToPlay];
[theAudio play];

这无法播放音频。然而,巧合的是,当我紧接着显示 UIAlertView 时,我可以听到音频剪辑播放的前 2 秒。也就是说,我的应用程序加载后,我听到两秒钟的音频,然后弹出警报并切断音频。

所以看起来 AVAudioPlayer 代码似乎有些工作。

对发生的事情以及我如何简单地播放音频有任何想法吗?

最佳答案

问题是您正在使用 ARC,因此当变量超出范围时,AVAudioPlayer 将被释放。您必须将 theAudio 变量声明为实例变量,并在 viewDidLoad 中分配它。所以,在你的 .h 文件中:

@interface MyViewController : UIViewController {
    AVAudioPlayer *theAudio;
    ...
}
...
@end

然后,从您在 viewDidLoad 中分配 theAudio 的行中删除 AVAudioPlayer *。这将导致您的 View Controller 保留音频播放器,从而防止播放器在播放前被释放。

关于iphone - AVAudioPlayer 不加载声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705119/

相关文章:

objective-c - 保存用户名并通过 Objective C iPhone

iphone - predicateForEventsWithStartDate 函数 : Is this a bug?

iphone - 解析时跳过 XML 的某些内容

ios - GCD NSURLSession completionHandler block 返回值 null

ios - 替换父 View Controller

iphone - 如何使用 NSURLRequest/NSURLConnection 将 mp3 文件下载到应用程序?

iphone - 我如何通过 iphone 项目中的 obj c 方法更改 sqlite 数据库中的表

objective-c - 将 NSDictionary 保存到 plist

iphone - Grand Central Dispatch 异步与同步

ios - 在 swift 4 中将 UIImagePickerController 呈现给照片库后崩溃;隐私已添加到 info.plist