实现摄影视频 保存到本地
importUIKit
importAVFoundation
importPhotos
class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
// 视频输出
let fileOutput = AVCaptureMovieFileOutput()
// 录像按钮
var recordButton: UIButton!
// 正在录音
var isRecording = false
override func viewDidLoad() {
super.viewDidLoad()
// 设置预览画面
setUpPreview()
}
func setUpPreview() {
letvideoDevice =AVCaptureDevice.default(for:AVMediaType.video)
letaudioDevice =AVCaptureDevice.default(for:AVMediaType.audio)
do{
ifvideoDevice==nil||audioDevice==nil{
throwNSError(domain:"device error", code:-1, userInfo:nil)
}
letcaptureSession =AVCaptureSession()
// video inputを capture sessionに追加
letvideoInput =tryAVCaptureDeviceInput(device: videoDevice!)
captureSession.addInput(videoInput)
// audio inputを capture sessionに追加
letaudioInput =tryAVCaptureDeviceInput(device: audioDevice!)
captureSession.addInput(audioInput)
// max 30sec
self.fileOutput.maxRecordedDuration=CMTimeMake(value:30, timescale:1)
captureSession.addOutput(fileOutput)
// プレビュー
letvideoLayer :AVCaptureVideoPreviewLayer=AVCaptureVideoPreviewLayer(session: captureSession)
videoLayer.frame=self.view.bounds
videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.view.layer.addSublayer(videoLayer)
captureSession.startRunning()
setUpButton()
}catch{
// エラー処理
}
}
func setUpButton() {
recordButton=UIButton(frame:CGRect(x:0,y:0,width:120,height:50))
recordButton.backgroundColor = UIColor.gray
recordButton.layer.masksToBounds = true
recordButton.setTitle("録画開始", for:UIControl.State.normal)
recordButton.layer.cornerRadius = 20.0
recordButton.layer.position = CGPoint(x: self.view.bounds.width/2, y:self.view.bounds.height-50)
recordButton.addTarget(self, action:#selector(ViewController.onClickRecordButton(sender:)), for: .touchUpInside)
self.view.addSubview(recordButton)
}
@objc func onClickRecordButton(sender: UIButton) {
if!isRecording{
// 録画開始
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
letdocumentsDirectory = paths[0]asString
letfilePath :String? ="\(documentsDirectory)/temp.mp4"
letfileURL :NSURL=NSURL(fileURLWithPath: filePath!)
fileOutput.startRecording(to: fileURLasURL, recordingDelegate:self)
isRecording=true
changeButtonColor(target:recordButton, color:UIColor.red)
recordButton.setTitle("録画中", for: .normal)
}else{
// 録画終了
fileOutput.stopRecording()
isRecording=false
changeButtonColor(target:recordButton, color:UIColor.gray)
recordButton.setTitle("録画開始", for: .normal)
}
}
func changeButtonColor(target:UIButton, color:UIColor) {
target.backgroundColor= color
}
funcfileOutput(_output:AVCaptureFileOutput, didFinishRecordingTo outputFileURL:URL, from connections: [AVCaptureConnection], error:Error?) {
// ライブラリへ保存
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputFileURL)
}) { completed, errorin
ifcompleted {
print("Video is saved!")
}
}
}
}