在我的应用程序内的屏幕上,我有一个用于音乐的 AVAudioPlayer 和一个用于视频的 AVPlayer。用户可以换出不同的歌曲和不同的视频,但一次只能播放一首。他们可以在 avPlayer 上播放 audioPlayer 或观看视频。
我有 MPRemoteCommandCenter 在使用暂停/播放/ff/rewind 时都可以正常工作。问题是我无法在锁定屏幕上显示当前时间或持续时间。我试过了,但它没有说明将代码放在哪里。
这是我尝试过的,这样每次用户切换歌曲或视频时,我都会获得新项目的所有可用数据:
声音的-
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
}
视频-
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
}
MPRemoteCommandCenter 与 AVAudioSession 一起在 viewDidLoad 中设置