gpt4 book ai didi

ios - 自定义音效变量必须定义为属性?

转载 作者:行者123 更新时间:2023-11-29 12:54:27 26 4
gpt4 key购买 nike

我创建了一个自定义类来处理我的应用程序中的声音效果。在实现代码时,它根本不能作为局部变量工作。我将它定义为一个属性,它工作得很好。有没有一种方法可以让我在使用类时只使用局部变量?

音效.h

@interface SoundEffect : NSObject

- (id)initWithSoundNamed:(NSString *)soundName;
- (void)play;
- (void)pause;

@property (strong, nonatomic) AVAudioPlayer *player;
@property (strong, nonatomic) NSString *soundName;

@end

音效.m

@implementation SoundEffect

- (id)initWithSoundNamed:(NSString *)soundName {
self = [super init];
if (self) {
self.soundName = soundName;
[self initialize];
}
return self;
}

- (void)initialize {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath], self.soundName]];
NSError *error;
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (self.player == nil) {
NSLog(@"%@", error.localizedDescription);
}
}

- (void)play {
[self.player play];
}

- (void)pause {
[self.player pause];
}

@end

实现

self.effect = [[SoundEffect alloc] initWithSoundNamed:@"laserShot"];
[self.effect play];

最佳答案

这很不幸,但据我所知,没有办法解决这个问题。在 ARC 下,局部变量在方法返回时被释放,并且您的播放器在声音有机会播放之前被销毁。您必须将播放器声明为属性,以便保持对播放器的引用。

关于ios - 自定义音效变量必须定义为属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504718/

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