AVFoundation フレームワークを使って動画を撮影し、保存する例です。 録画途中でのプレビューもon/off できます。
Button "Record" | Action (Touch Up Inside) | tapRecord 関数 |
Button "Stop" | Action (Touch Up Inside) | tapStop 関数 |
Button "Preview" | Action (Touch Up Inside) | tapPreview 関数 |
Label | Outlet | myLabel変数 |
動画の撮影と録画に関するコードを赤い文字で、 録画中にプレビューを背景全体に表示するコードをマゼンタ色の文字で示しています。
ViewController.swiftに追加するコード(赤字部分とマゼンタ字部分) |
import UIKit import AVFoundation class ViewController: UIViewController,AVCaptureFileOutputRecordingDelegate { var session: AVCaptureSession! var videoDevice: AVCaptureDevice! var audioDevice: AVCaptureDevice! var videoInput: AVCaptureDeviceInput! var audioInput: AVCaptureDeviceInput! var fileOutput: AVCaptureMovieFileOutput! var filePath: String! var previewFlag: Bool = false; var previewLayer: AVCaptureVideoPreviewLayer! @IBOutlet weak var myLabel: UILabel! @IBAction func tapRecord(sender: AnyObject) { print("recording started") myLabel.text = "recording started" filePath = NSHomeDirectory() + "/Documents/test.mp4" let fileURL: NSURL = NSURL(fileURLWithPath: filePath) session.startRunning() fileOutput.startRecordingToOutputFileURL(fileURL, recordingDelegate: self) } @IBAction func tapStop(sender: AnyObject) { fileOutput.stopRecording() session.stopRunning() UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, #selector(ViewController.video(_:didFinishSavingWithError:contextInfo:)), nil) } @IBAction func tapPreview(sender: AnyObject) { if previewFlag { previewLayer.removeFromSuperlayer() } else { view.layer.insertSublayer(previewLayer,atIndex:0) } previewFlag = !previewFlag } func captureOutput(captureOutput: AVCaptureFileOutput, didFinishRecordingToOutputFileAtURL outputFile: NSURL, fromConnections connections: [AnyObject]!,error: NSError) { print("recording finished") myLabel.text = "recording finished" } func video(videoPath: String, didFinishSavingWithError error: NSError!, contextInfo: UnsafeMutablePointer |