Hi, @breq
The ItemModel above is almost right, except there is no need to store the AVPlayer in it.
You can instantiate a single AVPlayer on app init, and set it as the player in a SwiftUI VideoPlayer instance.
Then, when you want to play a certain video, you create an AVAsset using the URL in the Item and set it as the AVPlayer current item using:
let asset = AVAsset(url: item.url)
let playerItem = AVPlayerItem(asset: asset)
player.replaceCurrentItem(with: playerItem)
As for knowing when it pauses and plays, you can use a rate change observer in the class holding your AVPlayer like this:
let name = AVPlayer.rateDidChangeNotification
for await _ in NotificationCenter.default.notifications(named: name) {
// in here you can read the player.rate, player.currentTime() and do your processing
}
Just remember that when the player is paused, it's rate == 0.0.
Also, you should never set the rate directly. Use .pause() and .play() instead because the user may have chosen a different playing speed on the UI...
Happy coding!
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: