我正在做一个需要播放很多短声音(mp3 文件)的应用程序。我正在使用 AvAudioPlayer 并且声音播放得很好,但是泄漏正在累积,直到我的应用程序崩溃。
我有一个单独的播放器类
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];
}
@结尾
然后我在我想要声音的视图中创建这个对象的实例。
在 .h 文件中,我添加以下行:
@class AVSnd;
AVSnd *mPlayer;
@property (nonatomic, retain) AVSnd *mPlayer;
在 .m 文件中我使用:
@synthezise mPlayer;
[self.mPlayer initWithMp3File:@"soundFileName"];
[self.mPlayer playNum:1];
[self.mPlayer release];
但是为什么每次播放声音时都会出现内存泄漏?我应该以另一种方式实现播放器吗?
非常感谢您的帮助!