Rhotick
Rhotick

Reputation: 177

Multiple AVPlayers on Separate UIViewControllers

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?

Upvotes: 0

Views: 386

Answers (2)

Tiago Almeida
Tiago Almeida

Reputation: 14237

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.

Upvotes: 1

Edwin Iskandar
Edwin Iskandar

Reputation: 4119

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.

Upvotes: 0

Related Questions