gpt4 book ai didi

ios - 从 ViewController 外部的类中使用 AVAudioPlayer 不起作用

转载 作者:行者123 更新时间:2023-11-29 12:15:37 24 4
gpt4 key购买 nike

iOS 和 Objective-C 的新手,一直在努力解决这个问题。我有一个类,它持有对 AVAudioPlayer 对象的强引用,并根据属于 UIButton 的参数“tag”定义了播放 mp3 的方法。在我的 View Controller 中,我有一个方法使用此类在按下按钮时播放声音。但是当我运行模拟器并按下按钮时,没有播放 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] 下面的答案也有效。

最佳答案

尝试像这样初始化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 或从您的类 GuitarTuner 创建一个单例,从那里一切都会容易得多。

也评论这个:

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

关于ios - 从 ViewController 外部的类中使用 AVAudioPlayer 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32080458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com