【发布时间】:2015-08-18 18:51:27
【问题描述】:
iOS 新手和Objective-C,一直在努力解决这个问题。我有一个类,它持有对AVAudioPlayer 对象的强引用,并根据属于UIButton 的参数“tag”定义了一个播放mp3 的方法。在我的视图控制器中,我有一个方法使用此类在按下按钮时播放声音。但是当我运行模拟器并按下按钮时,没有播放 mp3。当我不使用其他类并使AVAudioPlayer 属于我的ViewController 时,在viewDidLoad 中对其进行初始化,并在IBAction 方法中调用播放权,它工作正常。我检查了这些文件是否可用于我的项目,并且它们在代码中被正确引用。
我环顾四周,发现this 和this,都没有解决我的问题。这是我的代码
GuitarTuner.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface GuitarTuner : NSObject
- (void) play: (NSUInteger)tag;
@end
GuitarTuner.m
#import "GuitarTuner.h"
#import <AVFoundation/AVFoundation.h>
@interface GuitarTuner()
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@end
@implementation GuitarTuner
- (void) play:(NSUInteger)tag
{
NSString *note;
switch (tag) {
case 0:
note = @"Low-E";
break;
case 1:
note = @"A";
break;
case 2:
note = @"D";
break;
case 3:
note = @"G";
break;
case 4:
note = @"B";
break;
case 5:
note = @"Hi-E";
break;
}
NSString *path = [[NSBundle mainBundle] pathForResource:note ofType:@"mp3"];
NSURL *soundURL = [NSURL fileURLWithPath:path];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[self.audioPlayer play];
}
@end
ViewController.m
#import "ViewController.h"
#import "GuitarTuner.h"
@interface ViewController ()
@property (strong, nonatomic) GuitarTuner *tuner;
@end
@implementation ViewController
- (GuitarTuner *) tuner
{
if (!_tuner) return [[GuitarTuner alloc] init];
return _tuner;
}
- (IBAction)noteButton:(id)sender
{
UIButton *button = (UIButton*)sender;
[self.tuner play:button.tag];
}
@end
提前致谢
编辑:
愚蠢的错误!只是没有在 ViewController 的 getter 中正确初始化 GuitarTuner 属性——应该是_tuner = [[GuitarTuner alloc] init] 下面的答案也可以。
【问题讨论】:
标签: ios objective-c iphone avaudioplayer