AVAudioPlayer不加载声音 [英] AVAudioPlayer doesn't load sound

查看:94
本文介绍了AVAudioPlayer不加载声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For whatever reason, I'm having trouble loading up a sound with the AVAudioPlayer. I am testing it on my iPad device.

我的代码相当直接,没什么特别的。导入框架,实现委托。在我的 viewDidLoad 方法中:

My code is fairly straight forward, nothing fancy. The framework is imported, delegate implemented. In my viewDidLoad method:

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秒。也就是说,我的应用程序加载,我听到两秒钟的音频,然后警报弹出并切断音频。

This fails to play the audio. However, by coincidence, when I show a UIAlertView immediately after, I can hear the first 2 seconds of the audio clip play. That is, my app loads, I hear two seconds of audio, then the alert pops up and cuts off the audio.

所以看起来似乎 AVAudioPlayer 代码似乎有效。

So it would appear the AVAudioPlayer code somewhat seems to work.

有什么想法,我怎么能简单地播放音频?

Any idea on whats going on and how I can simply get the audio to play?

推荐答案

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

The problem is that you are using ARC, and therefore that the AVAudioPlayer is deallocated when the variable goes out of scope. You have to declare the theAudio variable as an instance variable, and assign it in the viewDidLoad. So, in your .h file:

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

然后,从viewDidLoad中指定 theAudio 的行中删除 AVAudioPlayer * 。这将导致视图控制器保留音频播放器,从而防止播放器在播放前被释放。

Then, get rid of the AVAudioPlayer * from the line where you assign theAudio in viewDidLoad. This will cause your view controller to retain the audio player, and thus will prevent the player from being deallocated before playback.

这篇关于AVAudioPlayer不加载声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆