I am having a nightmare with getting a video player to work in swiftUI where I can easily get video timestamp, hide video controls and play / pause the video easily.
Read if you want, but I have edited the post slightly more below: To tackle this I tried to implement my own video player in AVFoundation and then show that in a SwiftUI view, however, the code is a mess and I don't really understand it. It is hard to use and difficult to implement. To see my efforts I have linked a playground here: Playground Project Download Here for MacOS However, since this project has become such a mess, I was hoping that someone could explain / show how to:
- Create a video player from a URL - local / external.
- Play / Pause the video depending on the timestamp.
- Hide control
Here is some other code that I wrote just for displaying the video:
import SwiftUI
import AVKit
struct VideoView: View {
private let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!)
var body: some View {
VideoPlayer(player: player)
.onAppear() {
// Start the player going, otherwise controls don't appear
player.play()
}
.onDisappear() {
// Stop the player when the view disappears
player.pause()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
VideoView()
}
}
To remove the controls I added the modifier .disabled(true)
onto the VideoPlayer but it still shows for the first couple seconds, this isn't a nightmare but would be nice if it didn't show at all. But couldn't get the video to play / pause depending on the timestamp.
Ie. If video is at 1 minute then pause etc...
I found online that you can do something like this:
let currentPlayer = AVPlayer()
if let currentItem = currentPlayer.currentItem {
let duration = currentItem.asset.duration
}
let currentTime = currentPlayer.currentTime()
But I'm not sure how to implement it into the code above. Its' from: here
EDIT: I've tried to implement it like this in a playground on MacOS:
import SwiftUI
import PlaygroundSupport
import AVKit
struct VideoView: View {
private let player = AVPlayer(url: URL(string: "https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8")!)
var body: some View {
VideoPlayer(player: player)
.onAppear() {
// Start the player going, otherwise controls don't appear
player.play()
}
.onDisappear() {
// Stop the player when the view disappears
player.pause()
}
.onChange(of: player.currentTime(), perform: { value in
if let currentItem = player.currentItem {
let duration = currentItem.asset.duration
}
let currentTime = player.currentTime()
print (cmTimeToSeconds(currentTime))
})
//.disabled(true)
}
}
func cmTimeToSeconds(_ time: CMTime) -> TimeInterval? {
let seconds = CMTimeGetSeconds(time)
if seconds.isNaN {
return nil
}
return TimeInterval(seconds)
}
PlaygroundPage.current.setLiveView(VideoView())
But onChange
still isn't printing out the current time? Why is this?