Swift - How to get video dimension?

后端 未结 2 1196
野的像风
野的像风 2020-12-30 12:45

I am working on a video editing app where each video gets squared in such a way that no portion of the video gets cropped.For this, in case of portrait video, it contains bl

相关标签:
2条回答
  • 2020-12-30 13:38

    Try this:

    func initAspectRatioOfVideo(with fileURL: URL) -> Double {
      let resolution = resolutionForLocalVideo(url: fileURL)
      guard let width = resolution?.width, let height = resolution?.height else {
         return 0
      }
      return Double(height / width)
    }
    
    private func resolutionForLocalVideo(url: URL) -> CGSize? {
        guard let track = AVURLAsset(url: url).tracks(withMediaType: AVMediaType.video).first else { return nil }
       let size = track.naturalSize.applying(track.preferredTransform)
       return CGSize(width: abs(size.width), height: abs(size.height))
    }
    

    Hope it helps

    0 讨论(0)
  • 2020-12-30 13:48

    This is a more concise version of Vlad Pulichev's answer.

    var aspectRatio: CGFloat! // use the function to assign your variable
    
    func getVideoResolution(url: String) -> CGFloat? {
        guard let track = AVURLAsset(url: URL(string: url)!).tracks(withMediaType: AVMediaType.video).first else { return nil }
        let size = track.naturalSize.applying(track.preferredTransform)
        return abs(size.height) / abs(size.width)
    }
    
    0 讨论(0)
提交回复
热议问题