2

I think it has to do with ARC in iOS 5, but when I declare an AVAudioPlayer in a method and play it, it won't play. I think it gets released automatically at the end of the method because I don't remember this happening prior to iOS5. If I make it a global variable it works fine. Any way to use a local instance?

Marty
  • 5,926
  • 9
  • 53
  • 91

1 Answers1

2

Make it a retained property, and make your class the delegate, so you can clean up when it's done playing. In your header:

@interface MyClass : NSObject <AVAudioPlayerDelegate>
@property(strong)AVAudioPlayer *player;

Then, when you use it:

self.player = [AVAudioPlayer alloc] initWithContentsOfURL:URL error:&err];
[player setDelegate:self];

and clean it up in the delegate method:

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)playedSuccessfully {
    self.player = nil;
}

One nice thing about having it as a property is that you can interrupt it if you need to:

-(void)someInterruptionOccurred {
    [self.player stop];
}
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • but then it's still a global variable. i'm trying to declare it in the method. – Marty Oct 19 '11 at 18:42
  • A property is not a global variable. It's a member of the instance it's declared in. Why do you want to declare it in the method? – Christopher Pickslay Oct 19 '11 at 22:21
  • 1
    yeah that's what i meant, instance not global...global to the class. i don't NEED to declare it in the method, i just figured there's gotta be a way to do it since there was before. – Marty Oct 20 '11 at 05:44
  • If you declared it in the method before, it was almost certainly a memory leak. You either retained it and lost the reference at the end of the method scope, so you couldn't release it (memory leak), or you autoreleased it. But autoreleased AVAudioPlayers are almost always released before they're able to play the sound, unless perhaps it's very short. Under ARC, your local variables are implicitly __strong (retained) when declared, and are explicitly released at the end of the method block. – Christopher Pickslay Oct 20 '11 at 17:05