Skip to content

Instantly share code, notes, and snippets.

@gboyegadada
Last active November 14, 2023 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gboyegadada/e7b7343663b0e718b1ec8493d085216b to your computer and use it in GitHub Desktop.
Save gboyegadada/e7b7343663b0e718b1ec8493d085216b to your computer and use it in GitHub Desktop.
[ Swift for Mac OS ] Load video meta data from URL – duration, natural size and creation date (and more) in Swift. This looks expensive so make sure you store results somewhere for re-use. Bonus: get image pixel dimensions from (local image file) URL!
// For images...
import AppKit
extension URL {
func getImageSize() -> CGSize? {
guard let src = CGImageSourceCreateWithURL(self as CFURL, nil) else {
return nil
}
guard let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil),
let properties = props as? [String: AnyObject] else {
return nil
}
guard let w = properties["PixelWidth"], let h = properties["PixelHeight"] else {
return nil
}
let size = CGSize(
width: w.intValue as Int,
height: h.intValue as Int)
return size
}
}
// For video...
import AVKit
struct VideoInfo {
let isPlayable: Bool
let duration: Double
let creationDate: Date?
let size: CGSize?
}
extension URL {
func getVideoInfo() async -> VideoInfo? {
let asset = AVURLAsset(url: self)
do {
let (isPlayable, duration, tracks, creationDate) = try await asset.load(.isPlayable, .duration, .tracks, .creationDate)
let (naturalSize) = try await tracks.first?.load(.naturalSize)
let (date) = try await creationDate?.load(.dateValue)
return VideoInfo(
isPlayable: isPlayable,
duration: duration.seconds,
creationDate: date,
size: naturalSize
)
} catch {
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment