【问题标题】:Using AVAudioPlayer from class outside ViewController not working从 ViewController 外部的类中使用 AVAudioPlayer 不起作用
【发布时间】:2015-08-18 18:51:27
【问题描述】:

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

我环顾四周,发现thisthis,都没有解决我的问题。这是我的代码

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


    【解决方案1】:

    尝试像这样初始化AVAudioPlayer

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

    更新:

    你给自己答案:

    当我不使用其他类并使 AVAudioPlayer 属于 我的ViewController,在viewDidLoad中初始化,调用play right 在 IBAction 方法中,它工作正常。

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

    也评论一下:

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

    【讨论】:

    • 谢谢!在 viewDidLoad 中分配调谐器起到了作用,但现在我真的很困惑。为什么会这样?...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多