This has been upgraded to Swift 4.2 and converted to a URL extension.
import AVFoundation extension URL { var videoFrameCount: Int? { let asset = AVAsset(url: self) guard let assetTrack = asset.tracks(withMediaType: .video).first else { return nil } var assetReader: AVAssetReader? do { assetReader = try AVAssetReader(asset: asset) } catch { print(error.localizedDescription) return nil } let assetReaderOutputSettings = [ kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA) ] let assetReaderOutput = AVAssetReaderTrackOutput(track: assetTrack, outputSettings: assetReaderOutputSettings) assetReaderOutput.alwaysCopiesSampleData = false assetReader?.add(assetReaderOutput) assetReader?.startReading() var frameCount = 0 var sample: CMSampleBuffer? = assetReaderOutput.copyNextSampleBuffer() while (sample != nil) { frameCount += 1 sample = assetReaderOutput.copyNextSampleBuffer() } return frameCount } }
If he can convert the URL to an AVAsset type video , he will continue. Otherwise, nil is returned.
Then AVAssetReader is created. If this step fails, it will return nil again.
Since everything is set up correctly, he will now begin to analyze the output and count the frames. While the sample being produced, the cycle will continue to increase. Once the samples are no longer created, it completes the loop and returns a value for frameCount .
source share