Swift - 创建自定义捕获会话预设

时间:2017-07-05 04:57:57

标签: ios swift xcode

我想创建一个记录方形视频的自定义相机。但是,所有捕获会话预设都不是方格式

例如:

  • 1920×1080

  • 1280×720

  • 640×480

无论如何,我可以创建自定义预设。我仍然想要高质量的视频,但是方格式。最接近方格式的是640x480,但我仍然想要HD质量。

这是可能的,如果是这样的话怎么样?谢谢

1 个答案:

答案 0 :(得分:5)

导入必要的框架:

import UIKit
import AVFoundation
import Photos

比使用所需代表定义您的班级

class CameraViewController: UIViewController,
    AVCaptureAudioDataOutputSampleBufferDelegate,
    AVCaptureVideoDataOutputSampleBufferDelegate { }

您需要下一个属性来捕获并保存音频和视频流

private var session: AVCaptureSession = AVCaptureSession()
private var deviceInput: AVCaptureDeviceInput?
private var previewLayer: AVCaptureVideoPreviewLayer?
private var videoOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput()
private var audioOutput: AVCaptureAudioDataOutput = AVCaptureAudioDataOutput()

private var videoDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
private var audioConnection: AVCaptureConnection?
private var videoConnection: AVCaptureConnection?

private var assetWriter: AVAssetWriter?
private var audioInput: AVAssetWriterInput?
private var videoInput: AVAssetWriterInput?

private var fileManager: FileManager = FileManager()
private var recordingURL: URL?

private var isCameraRecording: Bool = false
private var isRecordingSessionStarted: Bool = false

private var recordingQueue = DispatchQueue(label: "recording.queue")

现在,您可以从AVCaptureSessionAVAssetWriter

的配置开始
self.session.sessionPreset = AVCaptureSessionPresetHigh     
self.recordingURL = URL(fileURLWithPath: "\(NSTemporaryDirectory() as String)/file.mov")
if self.fileManager.isDeletableFile(atPath: self.recordingURL!.path) {
    _ = try? self.fileManager.removeItem(atPath: self.recordingURL!.path)
}
self.assetWriter = try? AVAssetWriter(outputURL: self.recordingURL!,
    fileType: AVFileTypeQuickTimeMovie)

描述音频和视频设置。例如,我们将以全屏宽度制作正方形

let audioSettings = [
    AVFormatIDKey : kAudioFormatAppleIMA4,
    AVNumberOfChannelsKey : 1,
    AVSampleRateKey : 16000.0
] as [String : Any]

let videoSettings = [
    AVVideoCodecKey : AVVideoCodecH264,
    AVVideoWidthKey : UIScreen.main.bounds.width,
    AVVideoHeightKey : UIScreen.main.bounds.width
] as [String : Any]

将此设置添加到AVAssetWriterInput

self.videoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo,
     outputSettings: videoSettings)
self.audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio,
     outputSettings: audioSettings)

self.videoInput?.expectsMediaDataInRealTime = true
self.audioInput?.expectsMediaDataInRealTime = true

if self.assetWriter!.canAdd(self.videoInput!) {
    self.assetWriter?.add(self.videoInput!)
}

if self.assetWriter!.canAdd(self.audioInput!) {
    self.assetWriter?.add(self.audioInput!)
}

AVCaptureDeviceInput添加到您的会话

self.deviceInput = try? AVCaptureDeviceInput(device: self.videoDevice)
if self.session.canAddInput(self.deviceInput) {
    self.session.addInput(self.deviceInput)
}

现在,您可以将AVCaptureVideoPreviewLayer配置为正方形

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

//importent line of code what will did a trick
self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill

let rootLayer = self.view.layer
rootLayer.masksToBounds = true
self.previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width)

rootLayer.insertSublayer(self.previewLayer!, at: 0)
        otLayer.insertSublayer(self.previewLayer!, at: 0)

开始会话

self.session.startRunning()

将视频和音频输出添加到会话

DispatchQueue.main.async {
    self.session.beginConfiguration()

    if self.session.canAddOutput(self.videoOutput) {
        self.session.addOutput(self.videoOutput)
    }

    self.videoConnection = self.videoOutput.connection(withMediaType: AVMediaTypeVideo)
    if self.videoConnection?.isVideoStabilizationSupported == true {
        self.videoConnection?.preferredVideoStabilizationMode = .auto
    }
    self.session.commitConfiguration()

    let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
    let audioIn = try? AVCaptureDeviceInput(device: audioDevice)

    if self.session.canAddInput(audioIn) {
        self.session.addInput(audioIn)
    }

    if self.session.canAddOutput(self.audioOutput) {
        self.session.addOutput(self.audioOutput)
    }

    self.audioConnection = self.audioOutput.connection(withMediaType: AVMediaTypeAudio)
}

}

从这一点开始,您的相机已正确配置。您需要实现将记录视频和音频样本的下一个方法

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer
    sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {

if !self.isRecordingSessionStarted {
    let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
    self.assetWriter?.startSession(atSourceTime: presentationTime)
    self.isRecordingSessionStarted = true
}

let description = CMSampleBufferGetFormatDescription(sampleBuffer)!

if CMFormatDescriptionGetMediaType(description) == kCMMediaType_Audio {
    if self.audioInput!.isReadyForMoreMediaData {
        print("appendSampleBuffer audio");
        self.audioInput?.append(sampleBuffer)
    }
} else {
    if self.videoInput!.isReadyForMoreMediaData {
        print("appendSampleBuffer video");
        if !self.videoInput!.append(sampleBuffer) {
            print("Error writing video buffer");
        }
    }
}

}

添加将开始/停止录制的添加方法

private func startRecording() {
    if self.assetWriter?.startWriting() != true {
        print("error: \(self.assetWriter?.error.debugDescription ?? "")")
    }

    self.videoOutput.setSampleBufferDelegate(self, queue: self.recordingQueue)
    self.audioOutput.setSampleBufferDelegate(self, queue: self.recordingQueue)
}

private func stopRecording() {
    self.videoOutput.setSampleBufferDelegate(nil, queue: nil)
    self.audioOutput.setSampleBufferDelegate(nil, queue: nil)

    self.assetWriter?.finishWriting {
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.recordingURL!)
        }) { saved, error in
            if saved {
                let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alertController.addAction(defaultAction)
                self.present(alertController, animated: true, completion: nil)
            } else {
                print(error.debugDescription)
            }
        }
        print("saved")
    }
}

现在您可以从IBAction功能

开始/停止摄像机录制
@IBAction func recordingButton(_ sender: Any) {
    if self.isCameraRecording {
        self.stopRecording()
    } else {
        self.startRecording()
    }
    self.isCameraRecording = !self.isCameraRecording
}

以下是GitHub示例:https://github.com/ChernyshenkoTaras/CustomCamera