I successfully played an mp3 file within the body of a class. However, when I move the functionality out to a separate class, it fails.
Here’s the working code:
Header:
#import <AVFoundation/AVFoundation.h>
@interface QuestionController : UIViewController
<UITableViewDataSource, UITableViewDelegate, UISplitViewControllerDelegate>
{
AVAudioPlayer *audioPlayer;
}
working code:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/A.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog(@"audio errror: %@",[error description]);
else
[audioPlayer play];
Here’s the new class:
Header:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface AudioPlayer : NSObject {
}
- (void *) playAudioFile:(NSString *) mp3File;
@end
implementation:
#import "AudioPlayer.h"
@implementation AudioPlayer
- (void *) playAudioFile:(NSString *) mp3File {
NSLog(@"mp3file to play: %@", mp3File );
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", mp3File, [[NSBundle mainBundle] resourcePath]]];
NSError *error;
AVAudioPlayer *audioPlayer;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil) {
NSLog(@"audio errror: %@",[error description]);
}
else {
[audioPlayer play];
}
[audioPlayer release];
return 0;
}
@end
Here’s the calling code:
AudioPlayer *audioPlayer = [[AudioPlayer alloc] init];
[audioPlayer playAudioFile:@"/A.mp3"];
However, when it runs in the separate class, it doesn’t successfully create the player and goes to the “audio player == nil” branch
Here’s the output:
012-07-21 07:14:54.480 MyQuiz[6655:207] mp3file to play: /A.mp3
2012-07-21 07:15:40.827 MyQuiz[6655:207] audio errror: Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)"
The url is “file://localhost/A.mp3”
Any ideas what I’m doing wrong? I somehow have always have trouble when I’m refactoring to separate methods. It’s frustrating.
you have an error in the URL, change this line
to this: