开发者

AVAudioPlayer Leak and Crash

开发者 https://www.devze.com 2023-02-12 11:43 出处:网络
I want to play multiple audio files (.WAV) using IBAction and AVAudioPlayer. Unfortunatelly the sound plays but if I play the sound many times, my application crashes. Can you help me?

I want to play multiple audio files (.WAV) using IBAction and AVAudioPlayer. Unfortunatelly the sound plays but if I play the sound many times, my application crashes. Can you help me?

Here's my code.

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)audioPlayerDidFi开发者_如何学CnishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [player release];
}

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

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

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

@end


There are a couple things that look wrong in your code:

(1). There are no method Release, [Media Release] should be [Media release];

(2). If you play Sound2 while Sound1 is still playing, you leak Media instance:

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

This allocates new player and overwrites old one without releasing it first;

(3). It is usually bad idea to release calling object in delegate;

(4). I'd also suggest to rename Media to media and Path to path.

So playing action should look like this:


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

精彩评论

暂无评论...
验证码 换一张
取 消