声音在音板中停止工作(Xcode)

时间:2011-09-13 22:31:30

标签: objective-c xcode audio avaudioplayer

在我的音板应用程序中,一段时间后声音将停止工作,直到应用程序关闭并再次打开。无法弄清楚出了什么问题!这是我的代码:

在.h文件中:

(imported files here)

@interface MainView : UIView {

}
- (IBAction)pushButton2:(id)sender;

@end

在.m文件中:

(imported files here)


@implementation MainView

- (IBAction)pushButton2:(id)sender {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];

}

@end

1 个答案:

答案 0 :(得分:1)

我不确定它会导致您看到的行为,但每次按下该按钮时,您肯定会泄漏AVAudioPlayer。另外,我只需加载一次(例如,在viewDidLoad中),而不是按下每个按钮。也许是这样的事情:

@interface MainView : UIView
{
    AVAudioPlayer* audioPlayer;
}
- (IBAction)pushButton2:(id)sender;
@end

@implementation MainView

- (void) viewDidLoad
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sound1" ofType:@"mp3"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    audioPlayer.delegate = self;

}

- (void) viewDidUnload
{
    [audioPlayer release], audioPlayer = nil;
}

- (IBAction)pushButton2:(id)sender 
{
    [audioPlayer play];
}

@end