Swift AVFoundation currentTme


I’m making an audiobook app for iOS17 is having a problem in my AudioPlayerService.

Every second there is a spike in CPU usage when I run this code to update current playback position to the currentTime, which is a @Published var that I use to show playback position in my interface using a slider. Any ideas what might cause the error? The Time Profiler tells me the cpu usage is on directly on the main thread.

Is the correct way to show a slider that updates position every second by having a published variable directly in the AudioPlayerService? Or should slider/playback position be handled in the context of the slider?

Really thankful for any input here! Also let me know if you need more context.

private func addPlayerTimeObserver() {
    print("Debug: Adding player time observer")
    let interval = CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
    playerTimeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
        guard let strongSelf = self else { return }
        strongSelf.currentTime = time.seconds
        if let duration = strongSelf.player?.currentItem?.duration.seconds, duration.isFinite {
            strongSelf.totalDuration = duration
        }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img