views:

47

answers:

1

Hi!

Im doing an application that needs to play alot of short sounds (mp3-files). Im using AvAudioPlayer and the sounds are playing just fine, BUT the leaks are building up until my app crashes.

I have a seperate class for the player

AVSnd.h

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface AVSoundPlayer : NSObject <AVAudioPlayerDelegate> {
  AVAudioPlayer *msoundPlayer;
}
@property (nonatomic, retain) AVAudioPlayer *msoundPlayer;
-(id)initWithMp3File: (NSString *)inString;
-(void) playNum:(int)num;
@end



AVSND.m

@implementation AVSoundPlayer
@synthesize msoundPlayer;

-(id)initWithMp3File: (NSString *)fileName{
  if (self = [super init]){
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSError *error;
    NSURL *sURL = [NSURL fileURLWithPath:[mainBundle
                       pathForResource:fileName ofType:@"mp3"]];
    self.msoundPlayer = [[AVAudioPlayer alloc]
                        initWithContentsOfURL:sURL error:&error];
    if (!self.msoundPlayer) {
      NSLog(@"Sound player problem: %@", [error localizedDescription]);
    }
  }
  return self;
}

-(void) playNum:(int)num{
  self.msoundPlayer.numberOfLoops = num;
  [self.msoundPlayer prepareToPlay];
  AVAudioPlayer *tmpPlayer = self.msoundPlayer;
  [tmpPlayer play];
}

- (void)dealloc {
  [self.msoundPlayer release];
  [super dealloc];
}

@end

Then I make an instance of this object in the views i want sound.

in .h files I add following lines:

@class AVSnd;
AVSnd *mPlayer;
@property (nonatomic, retain) AVSnd *mPlayer;

and in .m files i use:

@synthezise mPlayer;
[self.mPlayer initWithMp3File:@"soundFileName"];
[self.mPlayer playNum:1];
[self.mPlayer release];

But why do I get memory-leaks every time i play a sound? Should i implement the player in another way?

Thank you so much for any help!

A: 
self.msoundPlayer = [[AVAudioPlayer alloc]
                    initWithContentsOfURL:sURL error:&error];

Here you are retaining the object twice, in self. (because of the property), and when alloc. It could be the reason.

toupper
I tried to change that line to:[self.msoundPlayer initWithContentsOfURL:sURL error:But still leaks.
Joakim Börjesson
If you do that you do not alloc memory ... Maybe with this:AVAudioPlayer *helper = [[AVAudioPlayer alloc] initWithContentsOfURL:sURL error:self.msoundPlayer = helper;[helper release];
toupper