Austinj
Austinj

Reputation: 43

Stop music from playing when leaving Initial View Controller (using AVAudioPlayer)

- (void)viewDidLoad {
       [super viewDidLoad];

    NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/Intro2.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;

    if (audioPlayer == nil)
        NSLog([error description]);
    else 
        [audioPlayer play];
}

My background music plays when the app loads the initial view controller, and loops fine. When I leave the initial view controller the music continues to play throughout the app, I would like for the music to stop when I leave the initial view controller.

Also, maybe it's unrelated, but I have an Issue (yellow !) on this line of code:

NSLog([error description]);

Upvotes: 1

Views: 3200

Answers (2)

sch
sch

Reputation: 27536

If the music continues to play, that means that the view controller is still retained. It is for example the root view controller of your navigation view controller.

To stop the music when the view controller is no longer displayed, you should use the method viewWillDisappear:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [audioPlayer stop]; // Or pause
}

If you want the music to resume when the view controller is displayed again, use the method viewWillAppear:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [audioPlayer play];
}

To remove the warning, change the line:

NSLog([error description]);

into:

NSLog(@"%@", [error description]);

Upvotes: 1

spring
spring

Reputation: 18517

Perhaps I am misunderstanding but you could simply use one of the UIView lifecycle events below to call stop on your instance of AVAudioPlayer.

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}

Upvotes: 0

Related Questions