Swift-AVAssetWriter保存视频

2023-09-19  本文已影响0人  T92
import UIKit
import AVFoundation

class ZGVideoWriter: NSObject {
    
    private var videoWriter: AVAssetWriter?
    private var videoWriterInput: AVAssetWriterInput?
    private var videoOutput: AVCaptureVideoDataOutput?
    private var isWritingStarted = false
    
    func setVideoOutputPath(outputPath: String){
        let outputURL = URL(fileURLWithPath: outputPath)
        do {
            videoWriter = try AVAssetWriter(url: outputURL, fileType: .mov)
        } catch {
            fatalError("Failed to create AVAssetWriter: \(error)")
        }
        let videoSettings: [String: Any] = [
            AVVideoCodecKey: AVVideoCodecType.h264,
            AVVideoWidthKey: 1080,
            AVVideoHeightKey: 1920
        ]
        videoWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
        if videoWriter!.canAdd(videoWriterInput!) {
            videoWriter?.add(videoWriterInput!)
        } else {
            fatalError("Failed to add videoWriterInput to AVAssetWriter")
        }
    }
    
    func writeSampleBuffer(sampleBuffer: CMSampleBuffer){
        if !isWritingStarted {
            videoWriter?.startWriting()
            videoWriter?.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))
            isWritingStarted = true
        }
        
        if videoWriterInput!.isReadyForMoreMediaData {
            if videoWriterInput!.append(sampleBuffer) {
            } else {
                print("Failed to append sample buffer")
            }
        }
    }
    
    func stopVideoWriting() {
        videoWriterInput?.markAsFinished()
        videoWriter?.finishWriting {[weak self] in
            if self?.videoWriter?.status == .completed {
                print("Video saved successfully")
                
            } else {
                print("Failed to save video: \(self?.videoWriter?.error?.localizedDescription ?? "")")
            }
            self?.isWritingStarted = false
        }
    }
}

使用

let videoWriter = ZGVideoWriter()
videoWriter.setVideoOutputPath(outputPath: "/\(your path).mov")
//采集到CMSampleBuffer后调用
videoWriter.writeSampleBuffer(sampleBuffer: sampleBuffer)
//停止采集调用
videoWriter.stopVideoWriting()
上一篇 下一篇

猜你喜欢

热点阅读