我想释放我为AVAudioPlayer分配的内存,但是当我尝试释放它时声音没有播放。这是潜在的内存泄漏,我怎么能摆脱这个。
这里下面的代码用于选择错误的选择然后我正在播放错误声音,如果我选择多次错误选择然后它被分配多次然后我怎么能摆脱这个。
else
{
NSString *soundName=@"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 :(得分:0)
您可以在名为audioDidFinishPlaying的avaudio播放器委托方法中发布。我完全不知道这个名字。但你可能会知道我在说什么
答案 1 :(得分:0)
使它成为你的类的保留属性,并在dealloc中释放它。
在您的标头文件中:
@property(retain)AVAudioPlayer *player;
在您的实现(.m)文件中:
@synthesize player;
在上面的代码中:
else
{
NSString *soundName=@"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];
}