降低视频的帧频,以在Swift中产生GIF感觉

时间:2019-05-24 20:53:52

标签: swift cocoa avkit

我一直试图将视频的帧速率降低到每秒10或15帧。 4/5年前有一些与OBJC相关的问题。我很快找不到任何东西。

这就是我在Playground上所做的工作

import Cocoa
import AVKit


var assetWriter:AVAssetWriter?
var assetReader:AVAssetReader?
let bitrate:NSNumber = NSNumber(value:8000000)

func compressFile(urlToCompress: URL, outputURL: URL, completion:@escaping (URL)->Void){

    var videoFinished = false

    let asset = AVAsset(url: urlToCompress);

    do{
        assetReader = try AVAssetReader(asset: asset)
    } catch{
        assetReader = nil
    }

    guard let reader = assetReader else{
        fatalError("Could not initalize asset reader probably failed its try catch")
    }

    let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first!

    let videoReaderSettings: [String:Any] =  [(kCVPixelBufferPixelFormatTypeKey as String?)!:kCVPixelFormatType_32ARGB ]

    let videoSettings:[String:Any] = [
        AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey:bitrate],
        AVVideoCodecKey: AVVideoCodecType.h264,
        AVVideoHeightKey: videoTrack.naturalSize.height,
        AVVideoWidthKey: videoTrack.naturalSize.width
    ]

    let assetReaderVideoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: videoReaderSettings)

    if reader.canAdd(assetReaderVideoOutput){
        reader.add(assetReaderVideoOutput)
    }else{
        fatalError("Couldn't add video output reader")
    }

    let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
    videoInput.transform = videoTrack.preferredTransform

    let videoInputQueue = DispatchQueue(label: "videoQueue")

    do{
        assetWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mov)
        assetWriter?.movieTimeScale = 1
    }catch{
        assetWriter = nil
    }
    guard let writer = assetWriter else{
        fatalError("assetWriter was nil")
    }

    writer.shouldOptimizeForNetworkUse = true
    writer.add(videoInput)


    writer.startWriting()
    reader.startReading()
    writer.startSession(atSourceTime: CMTime.zero)


    let closeWriter:()->Void = {
        // if (audioFinished && videoFinished){
        if (videoFinished){
            assetWriter?.finishWriting(completionHandler: {

                checkFileSize(sizeUrl: (assetWriter?.outputURL)!, message: "The file size of the compressed file is: ")
                completion((assetWriter?.outputURL)!)

            })

            assetReader?.cancelReading()

        }
    }

    videoInput.requestMediaDataWhenReady(on: videoInputQueue) {
        while(videoInput.isReadyForMoreMediaData){
            let sample = assetReaderVideoOutput.copyNextSampleBuffer()

            if (sample != nil){
                videoInput.append(sample!)
            }else{
                videoInput.markAsFinished()

                DispatchQueue.main.async {
                    videoFinished = true
                    closeWriter()
                }
                break;
            }
        }

    }


}

func checkFileSize(sizeUrl: URL, message:String){
    let data = NSData(contentsOf: sizeUrl)!
    print(message, (Double(data.length) / 1048576.0), " mb")
}


compressFile(urlToCompress: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video.mp4"), outputURL: URL(fileURLWithPath: "/Users/koraybirand/Desktop/video5.mp4")) { (URL) in

}

2 个答案:

答案 0 :(得分:0)

尝试在视频设置中添加AVVideoAverageNonDroppableFrameRateKey

答案 1 :(得分:0)

仅使用NextLevelSessionExporter ...声明它仅适用于IOS,但也适用于Mac Os X ...只需修改:

internal func createVideoComposition()
.......
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: Int32(frameRate))

用自己想要的值替换frameRate