Rhotick Rhotick - 1 month ago 10
iOS Question

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
?

Answer

In my opinion a singleton with only 1 AVPlayer solve 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.

Comments