Swift基础--视频录制

参考:Swift - 视频录制教程1

参考:if we're in zhe real pre-commit handler...

Demo下载

建议真机调试

  • AVCaptureSession视频捕获,inputoutput的桥梁
  • AVCaptureDevice音视频输入设备AVMediaTypeVideoAVMediaTypeAudio
  • AVCaptureMovieFileOutput implements the complete file recording
private let captureSession = AVCaptureSession()
private let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
private let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
private let fileOutPut = AVCaptureMovieFileOutput()
  • AVCaptureDeviceInput添加音视频输入设备,添加视频捕获输出
let videoInput = try! AVCaptureDeviceInput(device: videoDevice)        
let audioInput = try! AVCaptureDeviceInput(device: audioDevice) 

captureSession.addInput(videoInput)
captureSession.addInput(audioInput)        
captureSession.addOutput(fileOutPut)
  • AVCaptureVideoPreviewLayer图形界面,用于捕获视频展示
if let videoLayer = AVCaptureVideoPreviewLayer(session: captureSession) {
     videoLayer.frame = view.bounds
     videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
     view.layer.addSublayer(videoLayer)
}
  • 开始、停止拍摄
fileOutPut.startRecording(toOutputFileURL: fileUrl, recordingDelegate: self)

fileOutPut.stopRecording()
  • AVCaptureFileOutputRecordingDelegate 实现代理方法
func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!) {
        print("StartRecording 开始")
}
    
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
   var message:String!
   
   //将录制好的录像保存到照片库中
   PHPhotoLibrary.shared().performChanges({ 
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL)
   }) { (isSuccess:Bool, error:Error?) in
       if isSuccess {
           message = "保存成功"
       }else {
           message = "失败:\(String(describing: error?.localizedDescription))"
       }
       
       DispatchQueue.main.async {[weak self] in
           let alertVC = UIAlertController(title: message, message: nil, preferredStyle: .alert)
           let cancelAction = UIAlertAction(title: "sure", style: .cancel, handler: nil)
           alertVC.addAction(cancelAction)
           
           self?.present(alertVC, animated: true, completion: nil)
        }
    }
}

你可能感兴趣的:(Swift基础--视频录制)