录制视频时在前后摄像头之间切换(Snap / Stories - Instagram)

时间:2018-04-25 18:57:41

标签: ios swift xcode swift3 avcapturesession

我创建了一个自定义相机,我正在尝试添加一项功能,用户可以在录制视频时在前后相机之间切换。

但是当试图切换摄像机时,在切换功能中同样暂停并执行另一个视频,不允许我将它们组合在一个文件中并在最后播放而不会削减。

import UIKit
import AVFoundation
import CoreMedia

class VideoViewController: UIViewController, AVCaptureFileOutputRecordingDelegate,UITextFieldDelegate,UITextViewDelegate {

    @IBOutlet weak var previewView:UIView!
    @IBOutlet weak var recordButton: UIButton!
    @IBOutlet weak var toggleButton: UIButton!


    var captureSession = AVCaptureSession()
    var videoCaptureDevice:AVCaptureDevice?
    var previewLayer:AVCaptureVideoPreviewLayer?
    var movieFileOutput = AVCaptureMovieFileOutput()
    var outputFileLocation:URL?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.initializeCamera()

    }

    func dismissKeybord (){
    textView.resignFirstResponder()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillLayoutSubviews() {
        self.setVideoOrientation()
    }


    @IBAction func recordVideoButtonPressed(_ sender: AnyObject) {


        if self.movieFileOutput.isRecording {

            switchcamera = true

            self.movieFileOutput.stopRecording()

        } else {

            self.movieFileOutput.connection(withMediaType: AVMediaTypeVideo).videoOrientation = self.videoOrientation()

            self.movieFileOutput.maxRecordedDuration = self.maxRecordedDuration()

            self.movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath:self.videoFileLocation()), recordingDelegate: self)

        }

        self.updateRecordButtonTitle()

    }


    @IBAction func cameraTogglePressed(_ sender: AnyObject) {

        self.switchCameraInput()

    }


    @IBAction func btnGallery(_ sender: UIButton) {

        self.performSegue(withIdentifier: "videoPreview", sender: nil)

    }


    func initializeCamera(){

        self.captureSession.sessionPreset = AVCaptureSessionPresetHigh

        let discovery = AVCaptureDeviceDiscoverySession.init(deviceTypes: [AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified) as AVCaptureDeviceDiscoverySession

        for device in discovery.devices as [AVCaptureDevice] {

            if device.hasMediaType(AVMediaTypeVideo) {
                if device.position == AVCaptureDevicePosition.back {
                    self.videoCaptureDevice = device
                }
            }

        }

        if videoCaptureDevice != nil {
            do {
                try self.captureSession.addInput(AVCaptureDeviceInput(device: self.videoCaptureDevice))

                if let audioInput = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) {
                    try self.captureSession.addInput(AVCaptureDeviceInput(device: audioInput))
                }

                self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)

                self.previewView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)

                self.previewView.layer.addSublayer(self.previewLayer!)
                self.previewLayer?.frame = self.previewView.frame

                self.setVideoOrientation()

                self.captureSession.addOutput(self.movieFileOutput)

                self.captureSession.startRunning()

            } catch {
                print(error)
            }
        }

    }

    //Orientation Camera Record
    func setVideoOrientation() {
        if let connection = self.previewLayer?.connection {
            if connection.isVideoOrientationSupported {
                connection.videoOrientation = self.videoOrientation()
                self.previewLayer?.frame = self.view.bounds
            }
        }
    }

    //Switch Camrea function

    func switchCameraInput() {

        self.captureSession.beginConfiguration()

        var existingConnection:AVCaptureDeviceInput!

        for connection in self.captureSession.inputs {
            let input = connection as! AVCaptureDeviceInput
            if input.device.hasMediaType(AVMediaTypeVideo) {
                existingConnection = input
            }

        }

        self.captureSession.removeInput(existingConnection)

        var newCamera:AVCaptureDevice!
        if let oldCamera = existingConnection {
            if oldCamera.device.position == .back {
                newCamera = self.cameraWithPosition(position: .front)
            } else {
                newCamera = self.cameraWithPosition(position: .back)
            }
        }

        var newInput:AVCaptureDeviceInput!

        do {
            newInput = try AVCaptureDeviceInput(device: newCamera)
            self.captureSession.addInput(newInput)
        } catch {
            print(error)
        }

        self.captureSession.commitConfiguration()
    }

    //Capture Function Archive Library

    func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {

        print("Finished recording: \(outputFileURL)")


        self.outputFileLocation = outputFileURL
        //self.performSegue(withIdentifier: "videoPreview", sender: nil)

    }

    // Video Orientation Record

    func videoOrientation() -> AVCaptureVideoOrientation {

        var videoOrientation:AVCaptureVideoOrientation!

        let orientation:UIDeviceOrientation = UIDevice.current.orientation

        switch orientation {
        case .portrait:
            videoOrientation = .portrait
        case .landscapeRight:
            videoOrientation = .landscapeLeft
        case .landscapeLeft:
            videoOrientation = .landscapeRight
        case .portraitUpsideDown:
            videoOrientation = .portraitUpsideDown
        default:
            videoOrientation = .portrait
        }

        return videoOrientation

    }

    //Video Save Temp Library

    func videoFileLocation() -> String {
        return NSTemporaryDirectory().appending("prompterFile.mov")
    }

    // Record Funcition

    func updateRecordButtonTitle() {

        var isRecording = false

        if !self.movieFileOutput.isRecording {

            isRecording = true

        } else {

            isRecording = false

            stopScrolling()

            //Open Button Gallery

            btnGallery.isHidden = false
        }
    }


    func maxRecordedDuration() -> CMTime {
        let seconds : Int64 = 300
        let preferredTimeScale : Int32 = 1
        return CMTimeMake(seconds, preferredTimeScale)
    }

    func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice?
    {
        let discovery = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified) as AVCaptureDeviceDiscoverySession
        for device in discovery.devices as [AVCaptureDevice] {
            if device.position == position {
                return device
            }
        }

        return nil
    }


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {


        let preview = segue.destination as! VideoPreviewViewController
        preview.fileLocation = self.outputFileLocation
    }

}

0 个答案:

没有答案