tags:

views:

1754

answers:

3

Considering the code:

 soundFilePath = [[NSBundle mainBundle] pathForResource: @"Sound" ofType: @"wav"]; 
 fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; 
 avPlayerNextLevel = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL  error: nil];
 avPlayerNextLevel1.volume = volume ;
 [soundFilePath release];
 [fileURL release];

To play the sound I then do

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

I do this many times within my game. Sometimes on the simulator , the sound stops playing. And when sometimes I detect memory leaks with AvAudioPlayer.

Does everything look alright with my code ?

A: 
  1. Why are you releaseing a non-owning reference (soundFilePath)?
  2. You don't need to manually prepareToPlay if you're going to invoke play right after.

Quoting the documentation for play:

Discussion

Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.

Personally, I do this:

NSURL *soundUrl = [NSURL fileURLWithPath:
                   [[NSBundle mainBundle] pathForResource:track
                                                   ofType:nil]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl
                                                     error:nil];
[audioPlayer setDelegate:self];
[audioPlayer play];

Where audioPlayer is an ivar and track is an lvar of type NSString* which I obtained earlier from wherever I configure the next song to play.

lhunath
You are right, I have similar code and the releaseing of soundFilePath will cause an exception to occur when [player release] executes.
Mike
A: 

Hi,

I've been working on something similar but I was using a slightly different piece of code. Unfortunately, I got memory leaks, therefore I decided to give a try to the code you posted. Same result: memory leaks again when I invoke [audioPlayer play];

I can't really figure out what's going on. Are you guys aware of any memory leaks when AVAudioPlayer is involved?

+3  A: 

You'll need to release the instance of AVAudioPlayer that you created. Since the above code sets the delegate to self, just implement the following method and release there:

    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"Audio finished playing.");
    [player release];
}
Kyle