在 ViewController 之外使用来自 class 的 AVAudioPlayer 不工作

Using AVAudioPlayer from class outside ViewController not working

iOS 和 Objective-C 的新手,一直在努力解决这个问题。我有一个 class,它持有对 AVAudioPlayer 对象的强引用,并根据属于 UIButton 的参数 'tag' 定义了播放 mp3 的方法。在我的视图控制器中,我有一个方法使用此 class 在按下按钮时播放声音。但是当我 运行 模拟器并按下按钮时,没有播放 mp3。当我不使用其他 class 并使 AVAudioPlayer 属于我的 ViewController 时,在 viewDidLoad 中初始化它,并在 IBAction 中调用播放权方法,效果不错。我检查了这些文件是否可用于我的项目,并且它们在代码中被正确引用。

我环顾四周,发现 and 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] 下面的答案也有效。

尝试像这样初始化AVAudioPlayer

NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]
                     initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:note withExtension:@"mp3"] error:&error];

更新:

你给自己答案:

When I don't use the other class and make the AVAudioPlayer belong to my ViewController, initialize it in viewDidLoad, and call play right in the IBAction method, it works fine.

尝试在 viewDidLoad 中分配 tuner 或从您的 class GuitarTuner 创建一个单例,从那里一切都会容易得多。

也评论这个:

- (GuitarTuner *) tuner
{
    if (!_tuner) return [[GuitarTuner alloc] init];
    return _tuner;
}