I have a scenario when I play a single audio file and move to control center it works fine, but if goes back to view controller (player.pause() is called there) and came back and tried to other files it works on the same controller but in the control center previous file also playing simultaneously.
May be its because of AVPlayer objects, my handler called multiple times.
MPRemoteCommandCenter.shared().playCommand.addTarget { (playEvent) -> MPRemoteCommandHandlerStatus in
let currentItem = self.player.currentItem
self.player.replaceCurrentItem(with: currentItem)
if self.player.isPlaying {
self.player.pause()
}else{
self.player.play()
}
self.updateInfo()
self.btnAudioPlay.setImage(#imageLiteral(resourceName: "pause"), for: .normal)
return .success
}
MPRemoteCommandCenter.shared().pauseCommand.addTarget { (pauseEvent) -> MPRemoteCommandHandlerStatus in
if self.player.isPlaying {
self.player.pause()
}else{
self.player.play()
}
self.updateInfo()
self.btnAudioPlay.setImage(#imageLiteral(resourceName: "play"), for: .normal)
return .success
}
func updateInfo() {
let image = UIApplication.shared.icon!
let mediaArtwork = MPMediaItemArtwork(boundsSize: image.size) { (size: CGSize) -> UIImage in
return image
}
let nowPlayingInfo: [String: Any] = [
MPMediaItemPropertyAlbumTitle: self.subTilteForAudioPlayer,
MPMediaItemPropertyTitle: self.titleForAudioPlayer,
MPMediaItemPropertyArtwork: mediaArtwork,
MPMediaItemPropertyPlaybackDuration: Float(CMTimeGetSeconds((player.currentItem?.asset.duration)!)) ,
MPNowPlayingInfoPropertyElapsedPlaybackTime: Float(CMTimeGetSeconds(player.currentTime()))
]
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
The audio player gets initialized every time, it comes on the same screen so the multiple sounds are playing with Notification Center.
player = nil
above code works for me.