美文网首页
Swift-AVAssetWriter保存视频

Swift-AVAssetWriter保存视频

作者: T92 | 来源:发表于2023-09-19 09:57 被阅读0次
    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()
    

    相关文章

      网友评论

          本文标题:Swift-AVAssetWriter保存视频

          本文链接:https://www.haomeiwen.com/subject/mgynvdtx.html