2012-01-03 44 views
1

这对我来说是一个长期存在的问题,我一直无法解决。 我正在尝试播放一小段音频文件。但是,如果我不释放AVAudioPlayer,如果我释放它,文件根本无法播放,则会发生内存泄漏。在NSTimer中播放AVAudioPlayer,没有内存泄漏?

我试过autorelease,但没有任何工作。

- (void) playSoundShowLabel:(NSTimer*)theTimer { 

    NSMutableDictionary *dict = [[[NSMutableDictionary alloc] 
     initWithDictionary:[theTimer userInfo]] autorelease]; 

    NSURL *clickURL = [NSURL fileURLWithPath:[NSString 
     stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath], 
     [dict valueForKey:@"sWav"]]]; 

    AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: 
     clickURL error:nil]; 

    [theAudio play]; 
    theAudio.numberOfLoops = 0; 
    //[theAudio release]; << stops play 
} 

我曾尝试其他方法与系统播放声音文件,但我得到的其他问题这一点,所以我确实需要使用AVAudioPlayer

我用Google搜索这一点,但没有找到答案:(

回答

1

使用玩家的实例变量,并确保直到音频已完成或应中止其保持有效。

对于前者,利用其委托 - 对于后者,使用viewDidUnload或dealloc的

现在,我假设你没有使用ARC ...

在您接口声明:

@interface HoldingThePlayerSomeViewController : UIViewController <AVAudioPlayerDelegate> 
{ 
    AVAudioPlayer *theAudio; 
} 

在你的类实现:

- (void) playSoundShowLabel:(NSTimer*)theTimer 
{ 
    NSMutableDictionary *dict = [[[NSMutableDictionary alloc] 
     initWithDictionary:[theTimer userInfo]] autorelease]; 

    NSURL *clickURL = [NSURL fileURLWithPath:[NSString 
     stringWithFormat:@"%@/%@.mp3", [[NSBundle mainBundle] resourcePath], 
     [dict valueForKey:@"sWav"]]]; 

    [theAudio release]; 
    theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: 
     clickURL error:nil]; 
    theAudio.delegate = self; 

    [theAudio play]; 
    theAudio.numberOfLoops = 0; 
} 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
    if (player == theAudio) 
    { 
     [theAudio release]; 
     theAudio = nil; 
    } 
} 

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

你需要创建一个AVAudioPlayerDelegate得到所谓的背打了完成时。在那里你可以释放你的AVAudioPlayer。