3

I have an AVAudioPlayer instance attached with a view controller.

@property (nonatomic, retain) AVAudioPlayer *previewAudioPlayer;

I initialized it in -viewDidLoad.

NSError *error = nil;
AVAudioPlayer *aNewPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
self.previewAudioPlayer = aNewPlayer;
[aNewPlayer release];

[self.previewAudioPlayer prepareToPlay];

And, i release it in the view controllers -dealloc method.

- (void)dealloc {
    [_previewAudioPlayer pause];
    [_previewAudioPlayer release];

    [super dealloc];
}

Audio is played on a button click.

[self.previewAudioPlayer play];

Now, if the view controller is dismissed or pop'ed, dealloc should be called and audio player should stop and view controller should be destroyed. However, this doesn't happen. The audio doesn't stop, because the dealloc is not called until the audio stops playing. What's going on here? And, how can i make sure that if user is dismissing the controller than the audio stops.

1
  • Have you know how to play continues audio after destroyed that ViewController on we have created instance of AVPlayer. Feb 9, 2017 at 6:07

1 Answer 1

3

You can pause or stop the audio when the view gets dismissed, that is when the viewWillDisappear: or viewDidDisappear: methods get called.

- (void)viewWillDisappear:(BOOL)animated 
{
   [_previewAudioPlayer stop];
   [super viewWillDisappear:animated];
}
3
  • 1
    This does solve the problem, however i'm still looking for the answer to "Why isn't the dealloc method gets called". Thanks.
    – Mustafa
    Dec 12, 2011 at 11:29
  • Have you know how to play continues audio after destroyed that ViewController on we have created instance of AVPlayer. Feb 9, 2017 at 6:08
  • You'll probably have to keep the AVAudioPlayer instance alive somehow. If the view controller is the owner, when it dies, so it will the player. Feb 9, 2017 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.