AVAudioPlayer stops playing immediately with ARC

后端 未结 3 1257
心在旅途
心在旅途 2020-11-30 12:55

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:

  • For t
3条回答
  •  再見小時候
    2020-11-30 13:19

    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.

    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
    }
    

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

    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.

    More ARC information:
    Transitioning to ARC Release Notes
    LLVM Automatic Reference Counting

提交回复
热议问题