[swift] 스위프트에서 미디어 플레이어를 이용한 녹화 기능 추가하기

1. AVFoundation 불러오기

import AVFoundation

2. AVCaptureSession 생성하기

let captureSession = AVCaptureSession()

3. 사용할 장치 설정하기

guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }

4. AVCaptureDeviceInput 생성하기

do {
    let input = try AVCaptureDeviceInput(device: captureDevice)
    if captureSession.canAddInput(input) {
        captureSession.addInput(input)
    }
} catch {
    print(error)
    return
}

5. AVCaptureMovieFileOutput 생성하기

let output = AVCaptureMovieFileOutput()
if captureSession.canAddOutput(output) {
    captureSession.addOutput(output)
}

6. 미리보기 레이어 생성하기

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = .resizeAspectFill
previewLayer.frame = view.layer.bounds
view.layer.addSublayer(previewLayer)

7. 녹화 시작과 종료 메서드 생성하기

func startRecording() {
    if output.isRecording == false {
        let outputPath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("video.mp4")
        output.startRecording(to: outputPath, recordingDelegate: self)
    }
}

func stopRecording() {
    if output.isRecording == true {
        output.stopRecording()
    }
}

8. 세션 시작하기

captureSession.startRunning()

녹화 기능을 추가하는 더 많은 방법과 세부 설정에 대한 내용은 AVFoundation 공식 문서를 참조하세요.