【问题标题】:AVAudioPlayer Leak and CrashAVAudioPlayer 泄漏和崩溃
【发布时间】:2011-02-22 18:31:47
【问题描述】:

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

这是我的代码。

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

【问题讨论】:

    标签: iphone objective-c xcode memory-management avaudioplayer


    【解决方案1】:

    您的代码中有几处看起来有问题:

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

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

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

    这会分配新播放器并覆盖旧播放器而不先释放它;

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

    (4)。我还建议将 Media 重命名为 mediaPath 重命名为 path

    所以播放动作应该是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多