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

AVAudioPlayer崩溃
EN

Stack Overflow用户
提问于 2011-02-21 18:14:01
回答 2查看 2.1K关注 0票数 0

我的iOS应用程序有一个问题。我想播放多个音频文件(.WAV)使用IBActionAVAudioPlayer。不幸的是,声音会播放,但如果我多次播放声音,我的应用程序就会崩溃。也许是因为内存没有被正确释放。你能证实我的假设和/或告诉我如何解决这个问题吗?

这是我的密码。

ViewController.h

代码语言:javascript
复制
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>

@interface ViewController : UIViewController
{
    NSString        *Path;
}

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

@end

ViewController.m

代码语言:javascript
复制
#import <AVFoundation/AVAudioPlayer.h>
#import "ViewController.h"

@implementation ViewController

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

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

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

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

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

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

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

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

@end
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-21 18:19:44

问题是,您分配了大量的AVAudioPlayer实例,但没有发布任何实例。

您需要做的是将类设置为AVAudioPlayerDelegate,从类中删除媒体实例变量(相反,只需在各种IBAction方法中创建一个新实例变量),并按如下方式实现audioPlayerDidFinishPlaying:successfully:方法:

代码语言:javascript
复制
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [player release];
}

最后,更新代码,将类设置为您设置的每个AVAudioPlayers的委托,如下所示:

代码语言:javascript
复制
...
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media setDelegate:self];
[Media play];
...

通过这样做,您将确保发布您创建的所有AVAudioPlayer实例。

票数 4
EN

Stack Overflow用户

发布于 2011-02-21 18:17:49

媒体从不发布..。这导致了内存泄漏。使用SetterGetter方法,以便每当分配新对象时,就会释放前一个对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5069609

复制
相关文章

相似问题

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