2011-08-28 62 views
0

我有一個問題,不知道如何處理它。 Tyring用聲音和動畫製作應用程序。它給了我1級,然後2級的記憶警告。我已經嘗試過構建和分析,並且我得到了所有這些潛在的泄漏。如果我釋放音頻聲音將不會播放。任何提示?AVAudioPlayer泄漏?

下面是代碼的一部分,leakes由我有

- (IBAction)playsound2 
    { 
     NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"mp3"]; 
     AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
     *- **Method returns an Objective-C object with a +1 retain count (owning reference)*** 
     theAudio.delegate = self; 
     [theAudio play]; 

     ***- Object allocated on line 302 and stored into 'theAudio' is no longer referenced after this point and has a retain count of +1 (object leaked)*** 


     cat1.hidden = 0; 
     cat.hidden = 1; 
     [cat1 startAnimating]; 
     cat.center = cat1.center; 
     [self performSelector:@selector(loadAnimations) withObject:nil afterDelay:1.0]; 
     catLabel.hidden = 0; 
    } 

回答

6

Here是迄今問了同樣的問題的解決方案。

- (AVAudioPlayer *)audioPlayerWithContentsOfFile:(NSString *)path { 
     NSData *audioData = [NSData dataWithContentsOfFile:path]; 
     AVAudioPlayer *player = [AVAudioPlayer alloc]; 
     if([player initWithData:audioData error:NULL]) { 
      [player autorelease]; 
     } else { 
      [player release]; 
      player = nil; 
     } 
     return player; 
    } 

併爲更好的主意,你可以按照this.

+0

非常感謝,修好了! – ftwhere

0

您必須聲明爲AVAudioPlayer類實例的實例變量。

//Instance variable: 
{ 
    AVAudioPlayer* theAudio; 
} 

- (IBAction)playsound2 
{ 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"mp3"]; 
    if (!theAudio) { 
     theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
     if (theAudio) { 
      theAudio.delegate = self; 
      [theAudio play]; 
     } 
    } 

    cat1.hidden = 0; 
    cat.hidden = 1; 
    [cat1 startAnimating]; 
    cat.center = cat1.center; 
    [self performSelector:@selector(loadAnimations) withObject:nil afterDelay:1.0]; 
    catLabel.hidden = 0; 
}