0

I'm trying to play multiple songs in my app using multiple instances of MPMusicPlayerController.

I play the first song on the first player successfull but when I play the second song on the second player, the first one stops. It seems that only one MPMusicPlayerController could play something at a time but I can't find anything that could explain this fact.

Here is the code that I use to do this

func playItem(songID: String, playerIndex: Int){
  // I create an array of players and an array of descriptors so that every player could have a different descriptor.
  var players: [MPMusicPlayerController] = [];
  var descriptors: [MPMusicPlayerMediaItemQueueDescriptor] = [];
    
  // I recover the song using the id
  let song = getMediaItemsWithIDs(songIDs: [songID])

  // playerIndex is the index of the player that I'd like to use to play the song
  // If I try to use a player that doesn't exists I add one player and one descriptor to the relatives arrays (there is a control when the function is called so that the playerIndex is at the most one greater than the number of players in the array)
  if (players.count <= playerIndex) {
    players.append(MPMusicPlayerController.systemMusicPlayer)
    descriptors.append(MPMusicPlayerMediaItemQueueDescriptor(itemCollection: MPMediaItemCollection(items: song)))
  }

  // I replace the descriptor of the selected player with the selected song
  descriptors[playerIndex] = MPMusicPlayerMediaItemQueueDescriptor(itemCollection: MPMediaItemCollection(items: song))

  // I set the queue of the player with his descriptor and play the song
  players[playerIndex].setQueue(with: descriptors[playerIndex])
  players[playerIndex].prepareToPlay(completionHandler: {error in
    if error == nil {
      self.players[playerIndex].play()
    }
  })
}

I can't understand why this doesn't work, could someone help?

If this is not possible with MPMusicPlayerController or if you know what can I use I can switch to something else.

Thanks

MarcoF
  • 147
  • 9

0 Answers0