Reputation: 6119
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?
Upvotes: 2
Views: 1294
Reputation: 7510
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.
Upvotes: 11