我正在做一个需要播放很多短音(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];
}
@end
然后我在想要声音的视图中创建了这个对象的实例。
在.h文件中的我添加以下行:
@class AVSnd;
AVSnd *mPlayer;
@property (nonatomic, retain) AVSnd *mPlayer;
和我使用的.m文件:
@synthezise mPlayer;
[self.mPlayer initWithMp3File:@"soundFileName"];
[self.mPlayer playNum:1];
[self.mPlayer release];
但为什么每次播放声音都会出现内存泄漏?我应该以另一种方式实现播放器吗?
非常感谢您的帮助!
答案 0 :(得分:2)
我遇到了同样的问题并通过autorelease解决了它:
self.audioPlayer = [[[AVAudioPlayer alloc]
initWithContentsOfURL:url error:&error] autorelease];
答案 1 :(得分:1)
self.msoundPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:sURL error:&error];
在这里,你将自己保留两次。 (因为属性),以及何时分配。这可能是原因。