chum
chum

Reputation: 5

How do I stop the background music in another view in Xcode?

So I have a background music playing in one view, then I press the button and go to another view, the background music in another view run as well. Then I have two background music playing. I want to stop music from the previous view.

So here is the .h code for the first view:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController<AVAudioPlayerDelegate>{

AVAudioPlayer *startingMusic;

}

-(IBAction)StartGame:(id)sender;

So here is the .m code for the first view:

#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController

-(IBAction)StartGame:(id)sender{

}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

NSString *music = [[NSBundle mainBundle] pathForResource:@"Morning_Walk" ofType:@"mp3"];
startingMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
startingMusic.delegate=self;
startingMusic.numberOfLoops=-1;
[startingMusic play];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

here is the .h code for the second view:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface StageOne : UIViewController<AVAudioPlayerDelegate>

AVAudioPlayer *gameMusic;

}

here is the .m code for the second view:

#import "StageOne.h"
@interface StageOne ()

@end

@implementation StageOne

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

    // Custom initialization

}
return self;
}


- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

NSString *music = [[NSBundle mainBundle] pathForResource:@"Green_Hills" ofType:@"mp3"];
gameMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
gameMusic.delegate=self;
gameMusic.numberOfLoops=-1;
[gameMusic play];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

Thanks You so much!

Upvotes: 0

Views: 941

Answers (1)

skrew
skrew

Reputation: 889

This is normal behavior, as your first controller are still loaded

Try this:

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

    NSString *music = [[NSBundle mainBundle] pathForResource:@"Green_Hills" ofType:@"mp3"];
    gameMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
    gameMusic.delegate=self;
    gameMusic.numberOfLoops=-1;
    [gameMusic play];
}

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

    gameMusic.delegate = nil;
    [gameMusic stop];
    gameMusic = nil;
}

Upvotes: 1

Related Questions