gpt4 book ai didi

iphone - AVAudioPlayer 类中的错误?

转载 作者:行者123 更新时间:2023-12-03 20:58:26 28 4
gpt4 key购买 nike

我会保持简短和甜蜜 - 在我为自己购买 iPhone 开发者计划之前,我正在构建一个应用程序只是为了练习。

我正在尝试 AVFoundation.framework,但一直遇到一个错误,该错误只会让我播放在代码中初始化的第一个声音。你认为你们中有人可以帮助我吗?提前致谢!! :)

View Controller

-(IBAction)play {
if (segments.selectedSegmentIndex == 0) {
NSLog(@"Segment = 0");
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"meow" ofType:@"wav"];

if (path != nil) {
NSURL *url = [NSURL fileURLWithPath:path];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
[player prepareToPlay];
[player play];
}
}

else if (segments.selectedSegmentIndex == 1) {
NSLog(@"Segment = 1");
NSBundle *bundle = [NSBundle mainBundle];
NSString *path2 = [bundle pathForResource:@"meowloud" ofType:@"wav"];

if (path2 != nil) {
NSURL *url2 = [NSURL fileURLWithPath:path2];
AVAudioPlayer *player2 = [[AVAudioPlayer alloc]initWithContentsOfURL:url2 error:NULL];
[player2 prepareToPlay];
[player2 play];
// [player2 release];
}
}

text1.textColor = [UIColor clearColor];
text2.textColor = [UIColor clearColor];
text3.textColor = [UIColor clearColor];
text4.textColor = [UIColor clearColor];

}

执行此代码时,无论选择哪个段,都只会执行 meow.wav

最佳答案

您的代码存在一些内存泄漏。您在 play 方法中分配 AVAudioPlayer 的实例,但永远不会释放这些实例。请参阅Cocoa's memory management qguidelines了解详情。由于 AVAudioPlayer 实例需要保留在内存中才能播放,最简单的解决方案是向 viewController 类添加一个成员变量并将其设置为 retain 属性。

为了Don't Repeat Yourself (DRY) ,我还建议添加一个方法来封装播放单个 wav 文件所需的所有代码。

这是我编写此 View Controller 的方式:

MyViewController.h

@interface MyViewController : UIViewController
{
AVAudioPlayer *player;
}
@property(nonatomic, retain) AVAudioPlayer *player;
- (void)playWavFile:(NSString *)fileName;
- (IBAction)play;
@end

MyViewController.m

@synthesize player;

- (void)dealloc {
[player release];
}

- (void)playWavFile:(NSString *)fileName {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:fileName ofType:@"wav"];

if (path != nil) {
AVAudioPlayer *newPlayer;
NSURL *url = [NSURL fileURLWithPath:path];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url
error:NULL];
[self setPlayer:newPlayer];
[newPlayer release];

[newPlayer prepareToPlay];
[newPlayer play];
}
}

- (IBAction)play {

if (segments.selectedSegmentIndex == 0) {
[self playWavFile:@"meow"];
}
else if (segments.selectedSegmentIndex == 1) {
[self playWavFile:@"meowloud"];
}
}

关于iphone - AVAudioPlayer 类中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3153724/

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