how do i record record video with avassetwriter in swift

Here's an example code to record video with AVAssetWriter in Swift:

main.swift
import UIKit
import AVFoundation

class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {

    var videoWriter: AVAssetWriter!
    var videoWriterInput: AVAssetWriterInput!
    var pixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Instantiate AVAssetWriter
        do {
            videoWriter = try AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mp4)
        } catch let error {
            print(error.localizedDescription)
        }

        // Set video output settings
        let videoWidth = 640
        let videoHeight = 480
        let videoSettings: [String: Any] = [
            AVVideoCodecKey: AVVideoCodecType.h264,
            AVVideoWidthKey: videoWidth,
            AVVideoHeightKey: videoHeight
        ]
        videoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
        videoWriterInput.expectsMediaDataInRealTime = true

        // Add video input to the writer
        videoWriter.add(videoWriterInput)

        // Set pixel buffer adaptor settings
        let sourcePixelBufferAttributes: [String: Any] = [
            kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32ARGB), // or kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
            kCVPixelBufferWidthKey as String: videoWidth,
            kCVPixelBufferHeightKey as String: videoHeight
        ]
        pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: videoWriterInput,
                                                                  sourcePixelBufferAttributes: sourcePixelBufferAttributes)
        // Start recording
        videoWriter.startWriting()

        // Start a session
        videoWriter.startSession(atSourceTime: CMTime.zero)
    }

    // AVCaptureVideoDataOutputSampleBufferDelegate method to handle the sample buffer
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if videoWriterInput.isReadyForMoreMediaData {
            // Append the sample buffer to the writer input
            let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
            pixelBufferAdaptor.append(CMSampleBufferGetImageBuffer(sampleBuffer)!, withPresentationTime: presentationTime)
        }
    }

    func stopRecording() {
        // End the session
        videoWriterInput.markAsFinished()
        videoWriter.finishWriting {
            print("Video recorded: \(self.videoWriter.outputURL.path)")
        }
    }
}
2654 chars
66 lines

This code creates an AVAssetWriter, sets the video output settings, creates an AVAssetWriterInput for the video, starts the writing session and uses the captureOutput delegate method to append video frames to the input using the AVAssetWriterInputPixelBufferAdaptor. You can call stopRecording to stop the recording and finish writing the video to a file.

gistlibby LogSnag