On a screen inside my app I have both an AVAudioPlayer for music and an AVPlayer for videos. The user can swap out different songs and different videos but can only play one at a time. They can play either the audioPlayer or watch videos on the avPlayer.
I have MPRemoteCommandCenter that works fine for both when using pause/play/ff/rewind. The issue is I can't display the currentTime or duration for either on the lock screen. I tried this but it doesn't say where to put the code.
This is what I tried so that every time the user switches songs or videos I have all of the available data for the new items:
Audio-
do {
audioPlayer = try AVAudioPlayer(contentsOf: audioTrack)
audioPlayer?.delegate = self
audioPlayer?.prepareToPlay()
audioPlayer?.play()
setupNowPlayingForAudio()
} catch {
}
func setupNowPlayingForAudio() {
guard let audioPlayer = audioplayer else { return }
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "My App Name"
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = Float(audioPlayer.currentTime)
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = Float(audioPlayer.duration)
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = audioPlayer.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
Video-
playerStatusObserver = player?.observe(\.currentItem?.status, options: [.new, .old]) {
switch (player.status) {
case .readyToPlay:
player?.play()
setupNowPlayingForVideo()
}
}
func setupNowPlayingForVideo() {
guard let player = player, let playerItem = player.currentItem else { return }
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "My App Name"
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
The MPRemoteCommandCenter is set in viewDidLoad along with the AVAudioSession