0

Note: I have looked at other questions and the answers to them are quite vague or unhelpful

I have this code in View_Controller.h

@property AVAudioPlayer *playerSaxophone;

Then I do this in the same file (in viewDidLoad):

NSURL *backgroundMusicSaxophone = [NSURL fileURLWithPath:
                          [[NSBundle mainBundle]
                           pathForResource:@"saxophone" ofType:@"wav"]];
self.playerSaxophone = [[AVAudioPlayer alloc]
          initWithContentsOfURL:backgroundMusicSaxophone error:nil];

self.playerSaxophone.numberOfLoops = -1;

[self.playerSaxophone setVolume:0.5];
[self.playerSaxophone play];

In a different view controller I want to be able to stop or start this audio from playing by clicking 2 buttons. Is there any way I can do this?

Edit: I tried this in the "different" view controller .m file

//I do import ViewController.h in this file
- (IBAction)stop:(id)sender {
    ViewController *viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    [viewController.playerSaxophone stop];
}

But it didn't work.

Minestrone-Soup
  • 399
  • 1
  • 16

1 Answers1

0

You need to call:

[playerSaxophone stop];

to make the music stop.

Problem: Another view controller won't have a reference to playerSaxophone.

The fact that you want to add code that references this from another view controller means you'll have to find a way to have the three objects - view controller A, view controller B, and your audio player - communicate.

Here are a few options:

  1. Use the delegation pattern to have one view controller tell the other view controller to stop the player.
  2. The same as #1, but using the notification pattern. (This is ideal if you'd have a 3rd place that controls the player).
  3. You could move playerSaxophone to be a @property on either your App Delegate or a singleton. Then each view controller will be able to find it.

These are just a few solutions. There are others.

Additional reading:

Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • Your edit doesn't work because you're creating a *new* instance of `ViewController` instead of pointing to the one that you've already created. – Aaron Brager Dec 09 '14 at 02:50