Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer play/pause/stop and UIViewController release/dealloc

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.

like image 501
Mustafa Avatar asked Dec 10 '25 19:12

Mustafa


1 Answers

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];
}
like image 95
Fran Sevillano Avatar answered Dec 13 '25 10:12

Fran Sevillano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!