iosswiftvideompmovieplayercontrollervideo-processing

iOS Determine Number of Frames in Video


If I have a MPMoviePlayerController in Swift:

MPMoviePlayerController mp = MPMoviePlayerController(contentURL: url)

Is there a way I can get the number of frames within the video located at url? If not, is there some other way to determine the frame count?


Solution

  • I don't think MPMoviePlayerController can help you.

    Use an AVAssetReader and count the number of CMSampleBuffers it returns to you. You can configure it to not even decode the frames, effectively parsing the file, so it should be fast and memory efficient.

    Something like

        var asset = AVURLAsset(URL: url, options: nil)
        var reader = AVAssetReader(asset: asset, error: nil)
        var videoTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0] as! AVAssetTrack
    
        var readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: nil) // NB: nil, should give you raw frames
        reader.addOutput(readerOutput)
        reader.startReading()
    
        var nFrames = 0
    
        while true {
            var sampleBuffer = readerOutput.copyNextSampleBuffer()
            if sampleBuffer == nil {
                break
            }
    
            nFrames++
        }
    
        println("Num frames: \(nFrames)")
    

    Sorry if that's not idiomatic, I don't know swift.