首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AVAudioPlayer泄漏和崩溃

AVAudioPlayer泄漏和崩溃
EN

Stack Overflow用户
提问于 2011-02-22 18:31:47
回答 1查看 1.3K关注 0票数 0

我想播放多个音频文件(.WAV)使用IBActionAVAudioPlayer。不幸的是,声音会播放,但如果我多次播放声音,我的应用程序就会崩溃。你能帮帮我吗?

这是我的密码。

ViewController.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-22 20:22:09

在您的代码中,有几件事情看起来不太对劲:

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

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

代码语言:javascript
复制
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:...

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

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

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

所以玩动作应该是这样的:

代码语言:javascript
复制
- (IBAction)playSound1
{
    path = [[NSBundle mainBundle] pathForResource:@"Sound1" ofType:@"wav"];
    media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    [media play];
    [media release];
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5082265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档