AVAudioPlayer doesn't load sound

本秂侑毒 提交于 2019-12-11 02:42:50

问题


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

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];

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.

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/8705119/avaudioplayer-doesnt-load-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!