0

I have multiple AVPlayers, each on separate UIViewControllers playing different songs.
I need to pause one AVPlayer whenever I play another one (otherwise the audio overlaps).
I would like to let the user traverse through the app while the music plays in the background, so pausing the AVPlayer on viewDidDisappear:(BOOL)animated, would not work.
What is the best way to access the controls of each separate AVPlayer?

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Rhotick
  • 177
  • 1
  • 1
  • 6
  • It's not exactly what you want or need, but check this example, it might give some guidance: http://stackoverflow.com/questions/9877110/objective-c-need-help-creating-an-avaudioplayer-singleton/9880450#9880450 – Wolfgang Schreurs Nov 05 '13 at 18:08

2 Answers2

1

In my opinion a singleton with only 1 AVPlayer solves this issue well. This way you guarantee that to play another song you have to stop the previous. Then, in that AVPLayerSingleton you have a private property called avPlayer. You can define two methods:

- (void)createPlayerWithSong:(NSString *)currentSong;
- (void)destroyPlayer

Then, in your createPlayerWithSong you can check if avPlayer is already created and destroy it and create a new one for each new song.

Tiago Almeida
  • 14,081
  • 3
  • 67
  • 82
  • Wouldn't destroying the AVPlayer stop me from continuing the song where I left off? I want to pause it, not kill it. – Rhotick Nov 05 '13 at 18:27
  • Yes, it would. You can save the time where you stopped or have more AVPlayers. However I still believe that a singleton is a good option. – Tiago Almeida Nov 05 '13 at 18:40
0

Couple of ways you could do it:

Create a shared singleton object that have weak properties that reference each AVPlayer. That way you can control it from anywhere.

OR

Use NSNotificationCenter to send notifications when you want to control an AVPlayer on a different view controller. This might get cumbersome if you have a lot of AVPlayers you want to control.

Edwin Iskandar
  • 4,119
  • 1
  • 23
  • 24