gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:35:34 24 4
gpt4 key购买 nike

我在整个程序中都使用了一个声音文件:

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

因此,在我的.h文件中定义了soundFilePlayer1,因为我需要将其设置为全局文件。

现在...我需要释放soundFilePlayer1和soundFile1吗? (还有soundPath1?)

如果是这样,我该在哪里做?
我想我需要在以下位置释放soundFilePlayer1 :(但是我需要先停止它,因为当他们退出程序时它可能正在播放吗?)
- (void)dealloc {
[soundFilePlayer1 release];
}

那其他文件呢...我该在哪里释放这些文件呢?
谢谢

最佳答案

记住一个简单的经验法则。仅当在对象上调用了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中释放 soundFilePlayer1( dealloc),但是如果您不循环音频文件,则有更好的方法。符合 AVAudioPlayerDelegate:
@interface YourView : UIViewController <AVAudioPlayerDelegate> { //example

然后在此处实现该方法:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
//your audio file is done, you can release safely
[player release];
}

关于objective-c - Objective-c:如何为AvAudioPlayer释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6079257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com