我正在尝试根据使用 AVAudioPlayer 按下的按钮来播放声音。 (这不是音板或放屁应用程序。)
我在头文件中使用此代码链接了所有按钮:
@interface appViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
UIButton *C4;
UIButton *Bb4;
UIButton *B4;
UIButton *A4;
UIButton *Ab4;
UIButton *As4;
UIButton *G3;
UIButton *Gb3;
UIButton *Gs3;
UIButton *F3;
UIButton *Fs3;
UIButton *E3;
UIButton *Eb3;
UIButton *D3;
UIButton *Db3;
UIButton *Ds3;
UIButton *C3;
UIButton *Cs3;
}
@property (nonatomic, retain) AVAudioPlayer *player;
@property (nonatomic, retain) IBOutlet UIButton *C4;
@property (nonatomic, retain) IBOutlet UIButton *B4;
@property (nonatomic, retain) IBOutlet UIButton *Bb4;
@property (nonatomic, retain) IBOutlet UIButton *A4;
@property (nonatomic, retain) IBOutlet UIButton *Ab4;
@property (nonatomic, retain) IBOutlet UIButton *As4;
@property (nonatomic, retain) IBOutlet UIButton *G3;
@property (nonatomic, retain) IBOutlet UIButton *Gb3;
@property (nonatomic, retain) IBOutlet UIButton *Gs3;
@property (nonatomic, retain) IBOutlet UIButton *F3;
@property (nonatomic, retain) IBOutlet UIButton *Fs3;
@property (nonatomic, retain) IBOutlet UIButton *E3;
@property (nonatomic, retain) IBOutlet UIButton *Eb3;
@property (nonatomic, retain) IBOutlet UIButton *D3;
@property (nonatomic, retain) IBOutlet UIButton *Db3;
@property (nonatomic, retain) IBOutlet UIButton *Ds3;
@property (nonatomic, retain) IBOutlet UIButton *C3;
@property (nonatomic, retain) IBOutlet UIButton *Cs3;
- (IBAction) playNote;
@end
按钮都链接到 interfaceBuilder 中的事件“playNote”,并且每个笔记都根据笔记名称链接到正确的引用插座。
所有 *.mp3 声音文件均以 UIButton 名称 (IE-C3 == C3.mp3) 命名。
在我的实现文件中,当按下 C3 按钮时,我只播放一个音符:
#import "sonicfitViewController.h"
@implementation appViewController
@synthesize C3, Cs3, D3, Ds3, Db3, E3, Eb3, F3, Fs3, G3, Gs3, A4, Ab4, As4, B4, Bb4, C4;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:@"3C" ofType:@"mp3"];
NSLog(@"path: %@", path);
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer *p = [[AVAudioPlayer alloc]
initWithContentsOfURL:file error:nil];
[file release];
self.player = p;
[p release];
[player prepareToPlay];
[player setDelegate:self];
[super viewDidLoad];
}
- (IBAction) playNote {
[self.player play];
}
现在,有了上面我有两个问题:
- 首先,NSLog 在尝试播放文件时报告 NULL 并崩溃。我已将 mp3 添加到资源文件夹中,它们已被复制,而不仅仅是链接。它们不在资源文件夹下的子文件夹中。
其次,我该如何设置它,以便在按下按钮 C3 时播放 C3.mp3 而 F3 播放 F3.mp3 而无需为每个不同的按钮编写重复的代码行?playNote 应该像
NSString *path = [[NSBundle mainBundle] pathForResource:nameOfButton ofType:@"mp3"];
而不是专门定义它(@“C3”)。
有没有更好的方法来做到这一点,为什么当我加载应用程序时 *path 会报告 NULL 并崩溃?
我很确定这很简单,只需将额外的变量输入添加到 - (IBAction) playNote:buttonName 并将所有代码以调用 AVAudioPlayer 放在 playNote 函数中,但我不确定执行此操作的代码。