I am programming a Quiz-App. In the Menu-ViewController I added Music to the project. The musicPlayer is running well and as long as the Menu-ViewController is in front, I can also controle it (play, pause, stop, ect.). When I display another ViewController, the Music runs in the Background, like I'd like to. But if try to call the play/pause Method of the first ViewController being in the secondViewController, the music nether paused nor stoped. I don't know why! If I add other Instructions to this Method, everything's going fine. (I tried the exit(0);
Method. Here is my Code:
Controller 1 .h :
@implementation MenuViewController : <....> {
... }
@property (retain) AVAudioPlayer *backgroundPlayer;
- (void) playPauseMethod;
Controller 1 .m :
@interface ...
@end
@implementation MenuViewController
@ synthesize
- (void) soundChanger {
if (hintergrundPlayer.isPlaying) {
[backgroundPlayer pause];}
else if (!backgroundPlayer.isPlaying) {
[backgroundPlayer play];}}
Controller 2 .h :
#import "MenuViewController.h"
@interface QuizViewController : UIViewController{}
Controller 2 .m :
@interface ...
@end
@implementation MenuViewController
@ synthesize ...
//..... musicPlayer is playing music.
- (IBAction)myMusic:(id)sender {
//first try:
[[[MenuViewController alloc] init].backgroundPlayer pause];
//second try:
[[[MenuViewController alloc] init] soundChanger];}
I'd like to control the music in every ViewController. I'm looking forward to your help.
You're creating a completely new MenuViewController in Controller2 with
[[MenuViewController alloc] init]
The best way to handle it would be to set up a protocol in controller 2 with something like
@protocol <Controller2Delegate>
-(void) playButtonPressed:(id)self;
@end
Then set up a delegate property (still in controller 2) like this:
@property (weak) id <Controller2Delegate> delegate;
Then, back in Controller 1, when you create the Controller 2, set it's delegate property, like this:
QuizViewController *controller2 = [[QuizViewController alloc] init]];
controller2.delegate = self;
And then create the playButtonPressed method somewhere in controller 1. From Controller 2, you'll do something like:
[self.delegate playButtonPressed:self];
And that will call the method in Controller 1, where you can pause the background player.