Hi. I am trying to figure out how to make an AVAudioPlayer controllable (play, stop) throughout my app. I am doing this by starting it in my app delegate. The only thing is, I still get errors when I try to stop it in a different view controller. Here's how I did it:
MyAppDelegate.h:
Code:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
#import "MainMenu.h"
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
MainMenu *viewController;
AVAudioPlayer *backgroundMusic;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MainMenu *viewController;
@end
MyAppDelegate.m:
Code:
#import "MyAppDelegate.h"
#import "MainMenu.h"
@implementation MyAppDelegate
@synthesize window;
@synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
viewController = [[MainMenu alloc] init];
// Override point for customization after app launch
[window addSubview:[viewController view]];
[window makeKeyAndVisible];
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource: @"backgroundmusic" ofType: @"wav"];
NSURL *backgroundMusicURL = [[NSURL alloc] initFileURLWithPath:backgroundMusicPath];
backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:nil];
[backgroundMusic play];
backgroundMusic.numberOfLoops = -1;
backgroundMusic.volume = 0.5;
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
@end
------------------------
I want the backgroundMusic to play in the Main Menu (which, you could probably see, appears when the user starts the app, so that's why I started playing it in the delegate). However, when the user actually starts playing the game, I want it to stop (which is in a different view controller named level1). I get the variable by just doing #import MyAppDelegate.h into the level1.m file and did the normal [backgroundMusic stop]; to stop the music in the viewDidLoad method. However, backgroundMusic is still undeclared. I am at a complete loss. Sorry for this completely noob question. Thanks for the help in advance!