简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM