我的iOS应用程序有一个问题。我想播放多个音频文件(.WAV)使用IBAction和AVAudioPlayer。不幸的是,声音会播放,但如果我多次播放声音,我的应用程序就会崩溃。也许是因为内存没有被正确释放。你能证实我的假设和/或告诉我如何解决这个问题吗?
这是我的密码。
ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface ViewController : UIViewController
{
NSString *Path;
}
- (IBAction)Sound1;
- (IBAction)Sound2;
- (IBAction)Sound3;
- (IBAction)Sound4;
@endViewController.m
#import <AVFoundation/AVAudioPlayer.h>
#import "ViewController.h"
@implementation ViewController
- (IBAction)Sound1
{
Path = [[NSBundle mainBundle] pathForResource:@"Sound1" ofType:@"wav"];
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media play];
}
- (IBAction)Sound2
{
Path = [[NSBundle mainBundle] pathForResource:@"Sound2" ofType:@"wav"];
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media play];
}
- (IBAction)Sound3
{
Path = [[NSBundle mainBundle] pathForResource:@"Sound3" ofType:@"wav"];
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media play];
}
- (IBAction)Sound4
{
Path = [[NSBundle mainBundle] pathForResource:@"Sound4" ofType:@"wav"];
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[player release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)dealloc
{
[super dealloc];
}
@end发布于 2011-02-21 18:19:44
问题是,您分配了大量的AVAudioPlayer实例,但没有发布任何实例。
您需要做的是将类设置为AVAudioPlayerDelegate,从类中删除媒体实例变量(相反,只需在各种IBAction方法中创建一个新实例变量),并按如下方式实现audioPlayerDidFinishPlaying:successfully:方法:
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player release];
}最后,更新代码,将类设置为您设置的每个AVAudioPlayers的委托,如下所示:
...
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media setDelegate:self];
[Media play];
...通过这样做,您将确保发布您创建的所有AVAudioPlayer实例。
发布于 2011-02-21 18:17:49
媒体从不发布..。这导致了内存泄漏。使用SetterGetter方法,以便每当分配新对象时,就会释放前一个对象。
https://stackoverflow.com/questions/5069609
复制相似问题