'Syncing AVPlayer play (start) time with Timecode
I need my app to play a video (avplayer) at a specific time. Time in my app is represented through time code ("23:59:59:23").
I have a videos that need to play at specific timecode - for example video.mp4 start at 00:01:03:22 (minute 1, second 3, frame 22)
What I have tried so far: I have successfully setup my app to observe states within my avplayer based on this:media playback state
From what I've read I can achieve what I want by using AVPlayer.setRate. Although I really can't get my head around if this is what I need/how to use it.
My code below. Where I'm now stuck is what to do with everything you see from mulFactor to player.setRate. All taken from here. The below code plays all three of the videos in my app immediately. Assuming this is in fact the right way to achieve what I need, I'm guessing my next step will be replacing hostTime: with my timecodesource and time: with the time of playback????
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over status value
switch status {
case .readyToPlay:
// Player item is ready to play.
print("item is ready to play")
player.preroll(atRate: 1.0, completionHandler: {_ in print("prerolling avplayer")})
player.automaticallyWaitsToMinimizeStalling = false
let mulFactor = 24.0
let timeScale = CMTimeScale(mulFactor)
let seekCMTime = CMTime(value: CMTimeValue(CGFloat(1000.0)), timescale: timeScale)
let syncTime = CMClockGetHostTimeClock()
let hostTime = CMClockGetTime(syncTime)
player.setRate(1.0, time: seekCMTime, atHostTime: hostTime)
break
case .failed: break
// Player item failed. See error.
case .unknown: break
// Player item is not yet ready.
@unknown default:
print("FATAL ERROR IN AVPLAYER")
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|