2011-04-14 29 views
0

我想釋放我爲AVAudioPlayer分配的內存,但是當我試圖釋放它時,聲音沒有播放。這是潛在的內存泄漏,我怎麼能擺脫這個。如何在下面的代碼中發佈AVAudioPlayer

這裏下面的代碼是用來挑選錯誤的選擇,然後我播放錯誤的聲音,如果我選擇多次錯誤選擇然後它被分配多次,那麼我怎麼能擺脫這一點。

 else 
     { 
      NSString *[email protected]"Error.mp3"; 

      NSError *error; 
      NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%s", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]]; 

      AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error];// here I also used to release using autorelease then not played sound 

      worngAudioPlay.delegate = self; 

      if (worngAudioPlay == nil) 
      { 
      } 
      else 
      { 
       [worngAudioPlay play]; 
      } 
      // [worngAudioPlay release]; // Here I released then not played sound 
     } 

謝謝, Madan Mohan。

回答

0

您可以在名爲audioDidFinishPlaying的avaudio player委託方法中發佈。我完全不知道名字。但你可能會明白我在說什麼

+0

嗨,但是當我停下來然後這個方法不會被調用。 – 2011-04-14 09:32:20

+0

@馬丹莫漢閱讀文檔我不記得確切的方法名稱。你會發現在avaudioplayer類文檔 – 2011-04-14 09:56:14

0

使它成爲你的類的保留屬性,並在dealloc中釋放它。

在你的頭文件:

@property(retain)AVAudioPlayer *player; 

在您的實現(.M)文件:

@synthesize player; 

在上面的代碼:

else 
{ 
    NSString *[email protected]"Error.mp3"; 

    NSError *error; 
    NSURL *urlString = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%s", [[NSBundle mainBundle] resourcePath],[soundName UTF8String]]]; 

    AVAudioPlayer *worngAudioPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:urlString error:&error]; 

    if (worngAudioPlay != nil) 
    { 
     // this will cause the previous one to be released 
     [self setPlayer:worngAudioPlay]; 
     [worngAudioPlay release]; 
     worngAudioPlay.delegate = self; 
     [worngAudioPlay play]; 
    } 
} 

在你的dealloc:

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

我沒有setPlayer方法。我正在進行報警 – 2011-04-17 11:11:18

+0

如果您在頭文件中創建播放器屬性,並添加「@synthesize player;」到你的實現中,setHeader方法是隱式的。 – 2011-04-18 05:48:47