iOS Determine Number of Frames in Video

倾然丶 夕夏残阳落幕 提交于 2019-12-22 08:34:05

问题


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?


回答1:


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.




回答2:


Swift 5

 func getNumberOfFrames(url: URL) -> Int {
        let asset = AVURLAsset(url: url, options: nil)
        do {
            let reader = try AVAssetReader(asset: asset)
        //AVAssetReader(asset: asset, error: nil)
            let videoTrack = asset.tracks(withMediaType: AVMediaType.video)[0]

            let readerOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: nil) // NB: nil, should give you raw frames
            reader.add(readerOutput)
        reader.startReading()

        var nFrames = 0

        while true {
            let sampleBuffer = readerOutput.copyNextSampleBuffer()
            if sampleBuffer == nil {
                break
            }

            nFrames = nFrames+1
        }

        print("Num frames: \(nFrames)")
            return nFrames
        }catch {
            print("Error: \(error)")
        }
        return 0
    }


来源:https://stackoverflow.com/questions/29506411/ios-determine-number-of-frames-in-video

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!