I want to release the memory which I allocated for AVAudioPlayer, but when I tried to release it then the sound is not playing.It is potential memory leak, how can I get out of this.
here the below code is used when wrong selection is picked then I am playing the error sound, If I select multiple time wrong selection then It is allocated multiple times then how can I rid out of this.
else
{
NS开发者_如何学GoString *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
}
Thank you, Madan Mohan.
you can release in avaudio player delegate method named audioDidFinishPlaying. I don't know the name exactly. but you might get an idea what I am talking about
Make it a retained property of your class, and release it in the dealloc.
In your header file:
@property(retain)AVAudioPlayer *player;
In your implementation (.m) file:
@synthesize player;
In your code above:
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];
}
}
In your dealloc:
-(void)dealloc {
[player release];
[super dealloc];
}
精彩评论