Objective-c:如何为AvAudioPlayer释放内存

时间:2011-05-21 02:37:10

标签: objective-c memory-management audio

我有一个声音文件,我在整个程序中使用:

NSString *soundPath1 = [[NSBundle mainBundle] pathForResource:@"mysound" ofType:@"mp3"];
NSURL *soundFile1 = [[NSURL alloc] initFileURLWithPath:soundPath1];   
soundFilePlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile1 error:nil];
[soundFilePlayer1 prepareToPlay];   

所以soundFilePlayer1在我的.h文件中定义,因为我需要它是全局的。

现在......我需要发布soundFilePlayer1和soundFile1吗? (和soundPath1?)

如果是的话......我在哪里这样做? 我想我需要释放soundFilePlayer1 :(但我是否需要先停止它,因为它们可能在退出程序时播放?)

- (void)dealloc {
   [soundFilePlayer1 release];
}

其他文件怎么样?我在哪里发布这些文件? 感谢

1 个答案:

答案 0 :(得分:1)

记住一个简单的经验法则。仅在您在对象上调用allocinitnew时才会发布。因此,您需要发布soundFile1。或者,您可以使用便捷方法并将声音文件自动添加到自动释放池中:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
NSURL *file = [NSURL fileURLWithPath:path]; //autoreleased
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];

if([player prepareToPlay]){
    [player play];
}  

是的,您可以在player中发布soundFilePlayer1dealloc),但如果您没有循环播放音频文件,则可以采用更好的方法。符合AVAudioPlayerDelegate

@interface YourView : UIViewController <AVAudioPlayerDelegate> { //example

然后在这里实现方法:

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    //your audio file is done, you can release safely
    [player release];
}