2011-05-04 68 views
1

我正在使用AVAudioPlayer和我声音再次和安吉尔,并在我的应用程序调用此方法100次。问题是,我总是孤独,但当我要去释放,声音不起作用。 我该怎么办。AVAudioPlayer泄漏和警告,并在最后我的应用程序崩溃

-(void) ButtonSound 
{ 

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" 
     ofType:@"mp3"]; 
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
[player play]; 
[fileURL release]; 

} 

内存泄漏,应用程序崩溃,我想立即分配播放器并一次又一次地使用它。

回答

0
-(void) ButtonSound 
{ 

    NSBundle  *mainBundle = [NSBundle mainBundle]; 
    NSError   *error; 
    NSURL   *audioURL = [NSURL fileURLWithPath:[mainBundle pathForResource:@"Button1" ofType: @"mp3"]]; 
    AVAudioPlayer *player1 = [(AVAudioPlayer*) [AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error]; 
    self.player = player1; 
    [self.player play]; 
    [player1 release]; 
} 

这个代码是没有错误我还没有发现任何泄漏通过使用此代码

1

你的代码改成这样:

-(void) ButtonSound 
{ 
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" 
     ofType:@"mp3"]; 
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
    if (player) { 
     [player release]; 
    } 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
    [player play]; 
    [fileURL release]; 
} 

你还需要在你的dealloc方法来释放player。您还可能需要检查当您单击该按钮时是否已在播放player,如果是,则可能跳过此方法。

您可能还需要retain您的播放器对象,但这取决于您如何声明它(未在您的示例中显示)。

4

你可以做这样的事情

你头文件,宣布球员已经

AVAudioPlayer *buttonSoundPlayer; 

然后在执行

-(void)playButtonSound { 
    if(buttonSoundPlayer == nil) { 
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Button1" ofType:@"mp3"]; 
     NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath]; 
     buttonSoundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
     [fileURL release]; 
    } 
    [buttonSoundPlayer play]; 
}