AVAudioPlayer立即停止使用ARC播放

Phl*_*bbo 12 objective-c avfoundation avaudioplayer ios automatic-ref-counting

我正在尝试播放MP3,通过AVAudioPlayer它我认为相当简单.不幸的是,它并没有完全奏效.这就是我所做的一切:

  • 为了测试,我在Xcode中创建了一个新的iOS应用程序(Single View).
  • 我加入了AVFoundation框架到项目中,以及在#import <AVFoundation/AVFoundation.h>ViewController.m

  • 我在应用'文档'文件夹中添加了一个MP3文件.

  • 我改为ViewControllers viewDidLoad:以下内容:

码:

- (void)viewDidLoad
{
    [super viewDidLoad];        

    NSString* recorderFilePath = [NSString stringWithFormat:@"%@/MySound.mp3", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];    

    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:recorderFilePath] error:nil];
    audioPlayer.numberOfLoops = 1;

    [audioPlayer play];

    //[NSThread sleepForTimeInterval:20];
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,音频在开始播放后显然会立即停止.如果我取消注释sleepForTimeInterval它会播放20秒并在之后停止.只有在使用ARC进行编译时才会出现此问题,否则,它会完美无缺地运行.

Mat*_*man 7

问题是,在使用ARC进行编译时,您需要确保保留对要保持活动的实例的引用,因为编译器将alloc通过插入release调用自动修复"不平衡" (至少在概念上,阅读Mikes Ash博客文章了解更多详细信息)).您可以通过将实例分配给属性或实例变量来解决此问题.

在Phlibbo案例中,代码将转换为:

- (void)viewDidLoad
{
    [super viewDidLoad];        
    NSString* recorderFilePath = [NSString stringWithFormat:@"%@/MySound.mp3", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];    
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:recorderFilePath] error:nil];
    audioPlayer.numberOfLoops = 1;
    [audioPlayer play];
    [audioPlayer release]; // inserted by ARC
}
Run Code Online (Sandbox Code Playgroud)

而且AVAudioPlayer它会立即停止播放当没有提及离开它被释放.

我自己没有使用ARC,只是简单地阅读了它.如果您对此有更多了解,请对我的回答发表评论,我会更新更多信息.

更多ARC信息:
转换到ARC发行说明
LLVM自动引用计数