AVAudioPlayer立即停止播放ARC [英] AVAudioPlayer stops playing immediately with ARC

查看:83
本文介绍了AVAudioPlayer立即停止播放ARC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 AVAudioPlayer 播放MP3,我觉得这很简单。不幸的是,它并没有完全奏效。以下是我所做的一切:

I am trying to play an MP3 via AVAudioPlayer which I thought to be fairly simple. Unfortunately, it's not quite working. Here is all I did:


  • 为了测试,我在Xcode中创建了一个新的iOS应用程序(Single
    View) 。

  • 我将AVFoundation框架添加到项目中以及 #import
    < AVFoundation / AVFoundation.h>
    ViewController.m

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

I added an MP3 File to the Apps 'Documents' folder.

我更改了 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];
}

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

Unfortunately, the audio obviously stops right after it starts playing. If I uncomment the sleepForTimeInterval it plays for 20 seconds and stops afterwards. This problem occurs only when compiling with ARC, otherwise, it works flawlessly.

推荐答案

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

The problem is that when compiling with ARC you need to make sure to keep a reference to instances that you want to keep alive as the compiler will automatically fix "unbalanced" alloc by inserting release calls (at least conceptually, read Mikes Ash blog post for more details). You can solve this by assigning the instance to a property or a instance variable.

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

In Phlibbo case the code will be transformed into:

- (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
}

以及 AVAudioPlayer 它将立即停止播放,因为它在没有引用的情况下被释放。

And the AVAudioPlayer it will stop playing immediately as it gets deallocated when no reference is left.

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

I haven't used ARC myself and have just read about it briefly. Please comment on my answer if you know more about this and I will update it with more information.

更多ARC信息:

过渡到ARC发行说明

LLVM自动参考计数

这篇关于AVAudioPlayer立即停止播放ARC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆