Question

I'm trying to use AVAudioPlayer to play an mp3. Here is the code that I have:

- (void) playClip {
NSString *mp3File = [[NSBundle mainBundle] pathForResource:@"inFavor" ofType:@"mp3"];
AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:mp3File] error:NULL];
[avPlayer play];
}  

the name of the file that I'm referencing is "inFavor.mp3"

I'm a bit new to Objective-C so I'm not exactly sure why this isn't working. I'm using Xcode 5.

Was it helpful?

Solution

Make the AVAudioPlayer a property of the class so that it is not released when the function goes out of scope.

@property (strong, nonatomic) AVAudioPlayer* avPlayer;

Then initialize with

self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:mp3File] error:NULL];

OTHER TIPS

try this code, you need to check the error. paste the log you are getting in error

NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource:@"inFavor" 
                                              ofType:@"mp3"];
AVAudioPlayer* avPlayer = 
  [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]
                                         error:&error];
if (error) {
   NSLog(@"failed playing error: %@", error);
}else{
//avPlayer.delegate = self;
[avPlayer play];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top