2011-02-22 88 views
0

我想用IBActionAVAudioPlayer播放多個音頻文件(.WAV)。不幸的是聲音播放,但如果我多次播放聲音,我的應用程序崩潰。你可以幫我嗎?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 
+0

發佈堆棧跟蹤,請 – Max 2011-02-22 19:07:37

回答

2

有一對夫婦的事情,在你的代碼看上去是錯誤的:

(1)。沒有辦法發佈,[Media Release]應該是[Media release];

(2)。如果你玩SOUND2而Sound1例子仍在播放,您泄漏媒體實例:

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

這種分配新的球員,並覆蓋不首先釋放其舊;

(3)。在委託中釋放調用對象通常是個壞主意;

(4)。我也建議將Media重命名爲mediaPathpath

所以在播放動作應該是這樣的:


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