VideoRecorder

Please refer to the original information.
https://qiita.com/daigou26/items/74bbdfce46db8898fb47

Swift 5.2、1iOS 13.6

import UIKit
import AVFoundation
import Photos

class VideoViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
    let fileOutput = AVCaptureMovieFileOutput()
    var isRecording = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpPreview()
        
        // インターバルボタンが押された
        NotificationCenter.default.addObserver(self, selector:
            #selector(recButtonNotification(notification:)), name: .recButtonPressed, object: nil)
    }
    
    @objc func recButtonNotification(notification:Notification)
    {
        if !isRecording {
            let documentPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentPath.appendingPathComponent( "temp.mp4" )
            
            fileOutput.startRecording(to: fileURL, recordingDelegate: self)
            print("録画開始")
            isRecording = true
        } else {
            // 録画終了
            fileOutput.stopRecording()
            print("録画終了")
            isRecording = false
        }
    }
    
    func setUpPreview() {
        let videoDevice = AVCaptureDevice.default(for: AVMediaType.video)
        let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio)
        
        do {
            if videoDevice == nil || audioDevice == nil {
                throw NSError(domain: "device error", code: -1, userInfo: nil)
            }
            let captureSession = AVCaptureSession()
            
            // video inputを capture sessionに追加
            let videoInput = try AVCaptureDeviceInput(device: videoDevice!)
            captureSession.addInput(videoInput)
            
            // audio inputを capture sessionに追加
            let audioInput = try AVCaptureDeviceInput(device: audioDevice!)
            captureSession.addInput(audioInput)
            
            // ファイル出力を追加
            // 最大5秒で録画終了
            self.fileOutput.maxRecordedDuration = CMTimeMake(value: 5, timescale: 1)
            captureSession.addOutput(fileOutput)
            
            // プレビュー
            let videoLayer : AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            videoLayer.frame = self.view.bounds
            videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            self.view.layer.addSublayer(videoLayer)
            
            captureSession.startRunning()
        } catch {
            // エラー処理
        }
    }
    
    func changeButtonColor(target: UIButton, color: UIColor) {
        target.backgroundColor = color
    }
    
    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
        // ライブラリへ保存
        PHPhotoLibrary.shared().performChanges ({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL)
        }) { completed, error in
            if completed {
                print("Video is saved!")
            }
        }
    }
    
}

投稿者: admin

Free Software Engineer

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です