Initialize AVPlayerItem on the background to avoid hitches
Signed-off-by: Daniel D’Aquino <daniel@daquino.me>
This commit is contained in:
@@ -108,11 +108,24 @@ import SwiftUI
|
|||||||
|
|
||||||
public init(url: URL) {
|
public init(url: URL) {
|
||||||
self.url = url
|
self.url = url
|
||||||
self.player = AVPlayer(playerItem: AVPlayerItem(url: url))
|
// Initialize with an empty player first
|
||||||
|
self.player = AVPlayer()
|
||||||
self.video_size = nil
|
self.video_size = nil
|
||||||
|
|
||||||
|
// Creating the player item is an expensive action. Create it on a background thread to avoid performance issues.
|
||||||
|
Task.detached(priority: TaskPriority.userInitiated) {
|
||||||
|
self.loadPlayerItem(url: url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated private func loadPlayerItem(url: URL) {
|
||||||
|
let playerItem = AVPlayerItem(url: url)
|
||||||
|
|
||||||
|
DispatchQueue.main.async {
|
||||||
|
self.player.replaceCurrentItem(with: playerItem)
|
||||||
Task { await self.load() }
|
Task { await self.load() }
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func reinitializePlayer() {
|
func reinitializePlayer() {
|
||||||
Log.info("DamusVideoPlayer: Reinitializing internal player…", for: .video_coordination)
|
Log.info("DamusVideoPlayer: Reinitializing internal player…", for: .video_coordination)
|
||||||
@@ -122,12 +135,12 @@ import SwiftUI
|
|||||||
videoDurationObserver?.invalidate()
|
videoDurationObserver?.invalidate()
|
||||||
videoIsPlayingObserver?.invalidate()
|
videoIsPlayingObserver?.invalidate()
|
||||||
|
|
||||||
// Reset player
|
// Initialize player with nil item first
|
||||||
self.player = AVPlayer(playerItem: AVPlayerItem(url: url))
|
self.player.replaceCurrentItem(with: nil)
|
||||||
|
|
||||||
// Load once again
|
// Creating the player item is an expensive action. Create it on a background thread to avoid performance issues.
|
||||||
Task {
|
Task.detached(priority: TaskPriority.userInitiated) {
|
||||||
await load()
|
self.loadPlayerItem(url: self.url)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user