Mustafa
Mustafa

Reputation: 20564

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.

Upvotes: 3

Views: 1818

Answers (1)

Fran Sevillano
Fran Sevillano

Reputation: 8163

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];
}

Upvotes: 3

Related Questions