Add updating MediaPlayer info

This commit is contained in:
Arkadiusz Fal 2021-10-28 22:18:23 +02:00
parent 710f1f3630
commit f11125a399

View File

@ -2,6 +2,7 @@ import AVKit
import Defaults import Defaults
import Foundation import Foundation
import Logging import Logging
import MediaPlayer
#if !os(macOS) #if !os(macOS)
import UIKit import UIKit
#endif #endif
@ -45,6 +46,7 @@ final class PlayerModel: ObservableObject {
var composition = AVMutableComposition() var composition = AVMutableComposition()
private var currentArtwork: MPMediaItemArtwork?
private var frequentTimeObserver: Any? private var frequentTimeObserver: Any?
private var infrequentTimeObserver: Any? private var infrequentTimeObserver: Any?
private var playerTimeControlStatusObserver: Any? private var playerTimeControlStatusObserver: Any?
@ -136,6 +138,8 @@ final class PlayerModel: ObservableObject {
await self.loadComposition(stream, of: video, preservingTime: preservingTime) await self.loadComposition(stream, of: video, preservingTime: preservingTime)
} }
} }
updateCurrentArtwork()
} }
private func insertPlayerItem( private func insertPlayerItem(
@ -374,6 +378,7 @@ final class PlayerModel: ObservableObject {
return return
} }
self.updateNowPlayingInfo()
self.handleSegments(at: self.player.currentTime()) self.handleSegments(at: self.player.currentTime())
} }
} }
@ -429,4 +434,36 @@ final class PlayerModel: ObservableObject {
currentItem?.playbackTime = player.currentTime() currentItem?.playbackTime = player.currentTime()
currentItem?.videoDuration = player.currentItem?.asset.duration.seconds currentItem?.videoDuration = player.currentItem?.asset.duration.seconds
} }
fileprivate func updateNowPlayingInfo() {
let nowPlayingInfo: [String: AnyObject] = [
MPMediaItemPropertyTitle: currentItem.video.title as AnyObject,
MPMediaItemPropertyArtist: currentItem.video.author as AnyObject,
MPMediaItemPropertyArtwork: currentArtwork as AnyObject,
MPMediaItemPropertyPlaybackDuration: Int(currentItem.videoDuration ?? 0) as AnyObject,
MPNowPlayingInfoPropertyElapsedPlaybackTime: player.currentTime().seconds as AnyObject,
MPNowPlayingInfoPropertyPlaybackQueueCount: queue.count as AnyObject,
MPMediaItemPropertyMediaType: MPMediaType.anyVideo.rawValue as AnyObject
]
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
private func updateCurrentArtwork() {
guard let thumbnailData = try? Data(contentsOf: currentItem.video.thumbnailURL(quality: .medium)!) else {
return
}
#if os(macOS)
let image = NSImage(data: thumbnailData)
#else
let image = UIImage(data: thumbnailData)
#endif
if image.isNil {
return
}
currentArtwork = MPMediaItemArtwork(boundsSize: image!.size) { _ in image! }
}
} }