我成功地在一个类的正文中播放了一个 mp3 文件。但是,当我将功能移到单独的类时,它会失败。
这是工作代码:
标题:
#import <AVFoundation/AVFoundation.h>
@interface QuestionController : UIViewController
<UITableViewDataSource, UITableViewDelegate, UISplitViewControllerDelegate>
{
AVAudioPlayer *audioPlayer;
}
工作代码:
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];
这是新课程:
标题:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface AudioPlayer : NSObject {
}
- (void *) playAudioFile:(NSString *) mp3File;
@end
执行:
#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
这是调用代码:
AudioPlayer *audioPlayer = [[AudioPlayer alloc] init];
[audioPlayer playAudioFile:@"/A.mp3"];
但是,当它在单独的类中运行时,它没有成功创建播放器并转到“audio player == nil”分支
这是输出:
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.)"
网址是“file://localhost/A.mp3”
任何想法我做错了什么?当我重构为单独的方法时,我总是遇到麻烦。这令人沮丧。