我想播放多个音频文件(.WAV)使用IBAction和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;
@endViewController.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发布于 2011-02-22 20:22:09
在您的代码中,有几件事情看起来不太对劲:
(1)。没有方法发布,[Media Release]应该是[Media release];
(2)。如果在Sound2仍在播放时播放Sound1,则泄漏媒体实例:
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];
}https://stackoverflow.com/questions/5082265
复制相似问题