我的代码:
class Camera: UIViewController, UINavigationControllerDelegate, UIVideoEditorControllerDelegate, UIImagePickerControllerDelegate, AVCapturePhotoCaptureDelegate, AVCaptureFileOutputRecordingDelegate {
@IBOutlet weak var recordButton: UIBarButtonItem!
@IBOutlet weak var recordButtonLabel: UILabel!
var recording = false
var timer = Timer()
var time = 0.0
var captureSession = AVCaptureSession()
var sessionOutput = AVCapturePhotoOutput()
var previewLayer = AVCaptureVideoPreviewLayer()
let videoFileOutput = AVCaptureMovieFileOutput()
@IBOutlet weak var cameraView: UIView!
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
return
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidLoad()
let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.unspecified)
for device in (deviceDiscoverySession?.devices)! {
if (device as AnyObject).position == AVCaptureDevicePosition.back {
do{
let input = try AVCaptureDeviceInput(device: device )
if captureSession.canAddInput(input){
captureSession.addInput(input)
if captureSession.canAddOutput(sessionOutput){
captureSession.addOutput(sessionOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
}
}
catch{
print("Error displaying camera data")
}
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer.frame = cameraView.bounds
}
@IBAction func recordButton(_ sender: Any) {
if recording == false {
recordButton.tintColor = UIColor.red
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(Camera.processTimer), userInfo: nil, repeats: true)
recording = true
let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self
self.captureSession.addOutput(videoFileOutput)
let filePath = NSURL(fileURLWithPath: "filePath")
videoFileOutput.startRecording(toOutputFileURL: filePath as URL!, recordingDelegate: recordingDelegate)
} else if recording == true {
self.videoFileOutput.stopRecording()
recordButton.tintColor = UIColor(red: 22/255, green: 102/255, blue: 248/255, alpha: 1)
timer.invalidate()
time = 0
recording = false
}
}
}