Ive set a music track to play within the ViewController.h and .m files as shown below. I want to stop this when a new scene is loaded. (.h):
@interface ViewController : UIViewController<AVAudioPlayerDelegate>{
AVAudioPlayer *startingMusic;
}
@property (nonatomic, retain) AVAudioPlayer *startingMusic;
@end
and then .m
@synthesize startingMusic;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *music = [[NSBundle mainBundle] pathForResource:musicTrack ofType:@"mp3"];
startingMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
startingMusic.delegate=self;
startingMusic.numberOfLoops=-1;
[startingMusic play];
}
I then try and stop this from playing when the new scene loads is a different class called PlayLevel.m in an init method using this code.
ViewController *test = [[ViewController alloc] init];
[test.startingMusic stop];
However the music just continues to play when the new seen loads. Any suggestions?
You're going about this the wrong way around, you should really be stopping the music within ViewController
and not from another class. ViewController should be self contained where ever possible.
How are you loading the 2nd scene? I imagine you're using a Segue?
If you are using a segue you can override the function -prepareForSegue
which is a UIViewController
function. Within -prepareForSegue
stop the music then.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Stop Music
}