AVAudioPlayer泄漏和崩溃

时间:2011-02-22 18:31:47

标签: iphone objective-c xcode memory-management avaudioplayer

我想使用.WAVIBAction播放多个音频文件(AVAudioPlayer)。不幸的是声音播放但是如果我多次播放声音,我的应用程序崩溃了。你能救我吗?

这是我的代码。

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>

@interface ViewController : UIViewController <AVAudioPlayerDelegate>
{
    NSString        *Path;
}

- (IBAction)Sound1;
- (IBAction)Sound2;
- (IBAction)Sound3;
- (IBAction)Sound4;

@end

ViewController.m

#import <AVFoundation/AVAudioPlayer.h>
#import "ViewController.h"

@implementation ViewController

AVAudioPlayer *Media;

- (IBAction)Sound1
{
    Path = [[NSBundle mainBundle] pathForResource:@"Sound1" ofType:@"wav"];
    Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
    [Media setDelegate:self];
    [Media play];
}

- (IBAction)Sound2
{
    Path = [[NSBundle mainBundle] pathForResource:@"Sound2" ofType:@"wav"];
    Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
    [Media setDelegate:self];
    [Media play];
}

- (IBAction)Sound3
{
    Path = [[NSBundle mainBundle] pathForResource:@"Sound3" ofType:@"wav"];
    Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
    [Media setDelegate:self];
    [Media play];
}

- (IBAction)Sound4
{
    Path = [[NSBundle mainBundle] pathForResource:@"Sound4" ofType:@"wav"];
    Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
    [Media setDelegate:self];
    [Media play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)dealloc
{
    [Media Release];
    [super dealloc];
}

@end

1 个答案:

答案 0 :(得分:2)

您的代码中有一些错误:

(1)。没有方法发布,[Media Release]应为[Media release];

(2)。如果在Sound1仍在播放时播放Sound2,则会泄漏Media实例:

  
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:...
  

这会分配新玩家并覆盖旧玩家而不先释放它;

(3)。在委托中释放调用对象通常是个坏主意;

(4)。我还建议将Media重命名为media,将Path重命名为path

因此,播放动作应如下所示:


- (IBAction)playSound1
{
    path = [[NSBundle mainBundle] pathForResource:@"Sound1" ofType:@"wav"];
    media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    [media play];
    [media release];
}