2011-05-04 34 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]; 
}