Skip to content

Instantly share code, notes, and snippets.

@esnssr
Created February 24, 2026 13:05
Show Gist options
  • Select an option

  • Save esnssr/8ede0383b07d237fb31313c88e8850e0 to your computer and use it in GitHub Desktop.

Select an option

Save esnssr/8ede0383b07d237fb31313c88e8850e0 to your computer and use it in GitHub Desktop.
`AsyncStream` periodicTimeValues for AVPlayer
import Foundation
import AVFoundation
public extension AVPlayer {
func periodicTimeValues(
forInterval interval: CMTime,
queue: dispatch_queue_t? = nil
) -> AsyncStream<TimeInterval> {
let (stream, continuation) = AsyncStream.makeStream(of: Double.self)
nonisolated(unsafe) var timeObserver: Any? = self.addPeriodicTimeObserver(forInterval: interval, queue: queue) { time in
let seconds = time.seconds
if !seconds.isNaN && seconds.isFinite {
continuation.yield(seconds)
}
}
continuation.onTermination = { _ in
if let observer = timeObserver {
self.removeTimeObserver(observer)
timeObserver = nil
}
}
return stream
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment