MemoryLeak problem in following case - iphone

I am getting a memory leak when i click the play button....
I am testing with that "Leak" tool under "Run and performance tool"....on simulator
I am getting that leak when i click the play button first time.....
Here is my code....
-(IBAction)play
{
[self setPlayer];
[self playme];
}
-(IBAction)stop
{
[self stopme];
[self releasePlayer];
}
-(void)setPlayer
{
NSURL *file = [[NSURL alloc] initFileURLWithPath:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"shut up.mp3"]];
NSError *err = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err];
[file release];
player.numberOfLoops = -1;
[player prepareToPlay];
player.volume=1.0;
}
-(void)playme
{
if (!isPlaying)
{
[player play];
isPlaying=YES;
}
}
-(void)stopme
{
if (isPlaying)
{
[player stop];
isPlaying=NO;
}
}
-(void)releasePlayer
{
if(!isPlaying)
{
[player release];
player=nil;
}
isPlaying=NO;
}

I think, the below statement is the source of memory leak,
player = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err];
Here is the SO posts which has discussed the same issue.
AVAudioPlayer memory leak
AVAudioPlayer memory leak
AVAudioPlayer Memory Leak - Media Player Framework
Here is the blog post
AVAudioPlayer Memory Leak
EDITED:
As per the blog tutorial your code must be look like below.
-(void)setPlayer
{
NSURL *file = [[NSURL alloc] initFileURLWithPath:
[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"shut up.mp3"]];
NSError *err = nil;
NSData *data = [NSData dataWithContentsOfFile:file];
AVAudioPlayer *player = [AVAudioPlayer alloc];
if([player initWithData:audioData error:NULL])
{
player.numberOfLoops = -1;
[player prepareToPlay];
player.volume=1.0;
[player autorelease];
}
else
{
[player release];
player = nil;
}
[file release];
}
The leak-free version stores the pointer returned by alloc, rather than the pointer returned by initWithData:error:. That way, whatever happens, the player can still be released.

The blog post in Jhaliya's answer describes a leak that's specific to the situation when your player can't init the audio, for example when it can't find the file.
The real problem with your code is that you only release the player if the user explicitly stops the audio. If the audio plays through to the end, you have a player instance with a retainCount of 1. Then if the user hits play again, you create a new player and assign it to the player variable, leaking the old one.
The easiest solution to this is to make player a retained property:
#property(nonatomic,retain)AVAudioPlayer *player;
Then, instead of assigning to the ivar directly, use the mutator to set the player, which will implicitly release the previously set instance, if there is one:
[self setPlayer:[[[AVAudioPlayer alloc] initWithContentsOfURL:file error:&err] autorelease];
And don't forget to release it in your dealloc:
-(void)dealloc {
[player release];
[super dealloc];
}

Related

After recording audio and save to document directory unable to play audio file with AVAudioPlayer

I'm working on application which has record audio and play that recorded file which is store in document directory.
Here is my code:
Record button method.
(IBAction)stopButtonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
if (button.selected) { // Play recorded file.
self.stopButton.selected = NO;
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url error:&error];
self.audioPlayer.delegate = self;
self.audioPlayer.volume = 1.0;
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
}
else{ // Stop recording.
self.stopButton.selected = YES;
if (recordTimer) {
[recordTimer invalidate];
}
[self.audioPlayer stop];
self.recordButton.selected = NO;
[audioRecorder stop];
self.readyLabel.text = #"READY";
[self insertNewRecording];
}
}
I take it you're using ARC, in which case you'll need to retain the AVAudioPlayer as it sets to nil automatically. In your header file enter the following`
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
Hope this works for you,
Cheers Jim
um..I am not sure. But as a test, maybe you can try if you can play the file by specifying its name? E.g. you got a forest.mp3 to play and the key part of the code can be like this:
path = [[NSBundle mainBundle] pathForResource:#"forest" ofType:#"mp3"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:path];
NSError *audioError = nil;
av = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
If everything went well, maybe it's something to do with audioRecorder.url in your code?
Hope this gives you some ideas.

XCODE IOS memory leak for AVAudioPlayer

I use ARC.
Here is the method for starting the audio in my code:
.h file:
#property (retain,nonatomic)AVAudioPlayer *myAudio;
and .m files
-(void)myPlaySound:(NSString *)mySoundFile NumberOfLoops:(int)loopsCount ofType:(NSString *)fileType
{
if([myAudio isPlaying])
{
[myAudio stop];
}
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:mySoundFile
ofType:fileType]];
NSError *error;
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:&error];
self.theAudio = myAudio;
myAudio.volume = audioVolume;
myAudio.numberOfLoops = loopsCount;
myAudio.currentTime = 0.0;
[myAudio prepareToPlay];
if([myAudio play] == NO)
{
NSLog(#"error");
}
}
Based on the button press, I play different audio files of different length and bit rate and types.
Its working, but I get memory leak issue.

EXC_BAD_ACCESS after audioPlayerDidFinishPlaying: called

I have a class that I call to utilize AVAudioPlayer and everything works fine and dandy when it comes to playing the audio, but when the -audioPlayerDidFinishPlaying: is called my NSLog() command says that the player is released; the problem is that the app crashes moments later. I should mention that audioPlayer is an ivar in this class. Here is the code:
-(id) initWithFileName:(NSString *)sndFileName
{
[super init];
sndFileToPlay = [[NSString alloc] initWithString:sndFileName];
return self;
}
-(void)dealloc {
[audioPlayer release];
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
[super dealloc];
}
-(void)play
{
[self playSound:sndFileToPlay];
}
-(void)playSound:(NSString *)fileName
{
NSString *fname, *ext;
NSRange range = [fileName rangeOfString:#"."];
int location = range.location;
if( location > 0 )
{
fname = [fileName substringWithRange:NSMakeRange(0, location)];
ext = [fileName substringFromIndex:location+1];
[self playSound:fname :ext];
}
}
—
-(void)playSound:(NSString *)fileName :(NSString *)fileExt
{
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *fileURL = [NSURL fileURLWithPath:
[mainBundle pathForResource:fileName ofType:fileExt] isDirectory:NO];
if (fileURL != nil)
{
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
[audioPlayer setDelegate:self];
[audioPlayer play];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player
successfully:(BOOL)flag
{
NSLog(#"Releasing");
[audioPlayer release];
}
There are several things wrong with your code.
For one, in your dealloc:
[audioPlayer release];
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
You are releasing the audioPlayer, then, on the released (and maybe deallocated) player you set the delegate to nil and then the property, which releases it again. Remove the [audioPlayer release];.
In your audioPlayerDidFinishPlaying:successfully: you're releasing the player as well, but you haven't set the variable to nil. That might cause a crash since by the time you access this variable again a different object might be at that memory address. Use the property instead and do it like in your dealloc:
self.audioPlayer.delegate = nil;
self.audioPlayer = nil;
Then, in playSound:: (argh, non-named second argument !) you over-release fileURL. The -[NSURL fileURLWithPath:isDirectory:] returns an autoreleased object, you may not release it.
Last but maybe not least you leak sndFileToPlay, you need to release it in your dealloc method. And instead of sndFileToPlay = [[NSString alloc] initWithString:sndFileName]; simply do sndFileToPlay = [sndFileName copy];.
You might want to read up on Objective-C memory management. It's not hard once you know the three or four rules-of-thumb.
You should clean up your code. If playSound is called several times, you are leaking AVAudioPlayer.
In your dealloc, you should put [audioPlayer release] after the two lines beneath.
Turn on NSZombieEnabled to debug, and make sure that the audioPlayer is not released when didFinish is called.

stopping an AVAudioPlayer

here is my code
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"95" ofType:#"wav"];
NSError *activationError = nil;
NSError *audioPlayerInitError = nil;
[[AVAudioSession sharedInstance] setActive: YES error:&activationError];
NSURL *newURL = [NSURL fileURLWithPath:soundFilePath];
musicPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:newURL error:&audioPlayerInitError];
if (musicPlayer1) {
[musicPlayer1 stop];
[musicPlayer1 release];
musicPlayer1 = nil;
}
else {
[musicPlayer1 prepareToPlay];
[musicPlayer1 setVolume:.8];
[musicPlayer1 setNumberOfLoops:-1]; // -1 means play indefintely
[musicPlayer1 setDelegate: self];
[musicPlayer1 play];
}
}
I am rying to start and stop the AVAudioPlay with the same button (musicPlayer1 is in the header). Now when i touch the button it does not play anything. Help please?
You're creating a new instance of AVAudioPlayer each time. You need to hold onto the reference to the object somewhere, and refer back to that. Add a field to your view controller class:
#private AVAudioPlayer *currentAudio;
And then in this method, make the following changes:
if (currentAudio) {
[currentAudio stop];
[currentAudio release];
currentAudio = nil;
} else {
// what you already have goes here
}

Sounds randomly interrupted when starting to play

I'm calling playSoundFromBundle from the code below to play sounds (aif files). I have a sound that does a single click and then a fading sound. Both sounds are in the same file. Sometimes I get two clicks and then the fade. Meaning, click, click...fade. A single click isn't what should play. I'm guessing the sound starts (click sound), gets interrupted and then restarts (full sound...click/fade) because of other processing that may be going on. It seems random when it will occur. I put the sound on its own thread to try and avoid the double clicking. Is there anything else I can do to ensure the sound plays correctly?
- (void) playSoundFromBundleThreaded:(NSArray*)arr{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *fileName = (NSString*)[arr objectAtIndex:0];
NSString *fileExt = (NSString*)[arr objectAtIndex:1];
NSError *err;
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: fileName ofType: fileExt inDirectory:#"/"]] error: &err];
self.audioPlayer = newPlayer;
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = .5;
if (self.audioPlayer == nil)
{
NSLog(#"Problem initializing Sound - %#", [err description]);
}
else
{
[self.audioPlayer play];
}
[newPlayer release];
[pool release];
}
- (void) playSoundFromBundle:(NSString*)fileName fileExtension:(NSString*)fileExt{
NSArray *arr = [NSArray arrayWithObjects:fileName, fileExt, nil];
[NSThread detachNewThreadSelector: #selector(playSoundFromBundleThreaded:) toTarget:self withObject:arr];
}
No idea if this would work, but check out the Audio Session stuff. It's intended to manage things like whether the playing of other sounds (such as by the music player) will interrupt audio from your application.