1 自定义摄像头
AVFoundation
要想熟悉OC里面的框架 理解这个框架结构图必不可少 不过这是我盗过来的图 嘿嘿嘿 这是 AVFoundation 框架图
AVAudioToolBox
VideoToolBox
AVCaptureDevice
AVCaptureDeviceInput
AVCaptureSession
AVCaptureVideoPreviewLayer
// 输入设备
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
// 输入设备
let cameraDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let inputDevice = try AVCaptureDeviceInput(device: cameraDevice)
// 输出设备
let outputDevice = AVCaptureVideoDataOutput()
outputDevice.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String : NSNumber(value: kCVPixelFormatType_32BGRA)]
outputDevice.setSampleBufferDelegate(self, queue: DispatchQueue.main)
// capture session
let captureSession = AVCaptureSession()
captureSession.addInput(inputDevice)
captureSession.addOutput(outputDevice)
captureSession.beginConfiguration()
//设置分辨率
captureSession.canSetSessionPreset(AVCaptureSessionPreset1280x720)
// connection
if let connection = outputDevice.connection(withMediaType: AVMediaTypeVideo){
connection.videoOrientation = .portrait;
}
captureSession.commitConfiguration()
if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession){
previewLayer.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer.frame = self.view.bounds
self.view.layer.addSublayer(previewLayer)
}
captureSession.startRunning()
} catch _ {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: AVCaptureVideoDataOutputSampleBufferDelegate{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) {
}
}
项目中可能会报这样的错误
也不用慌张这是因为IOS在8.0之后加了视频 音频等设备的访问权限 在info.plist里面加上 这三条先
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
<key>NSContactsUsageDescription</key>
<string>contactsDesciption</string>
<key>NSMicrophoneUsageDescription</key>
<string>microphoneDesciption</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>photoLibraryDesciption</string>
获取的视频源会通过AVCaptureVideoDataOutputSampleBufferDelegate 代理生成
CMSampleBuffer 在这里我们可以通过 CMSampleBuffer实现视频截图功能这个功能可以自行百度这里不做展开 下一章介绍 CMSampleBuffer
附录 1 录制视频功能以及保存
这部分的功能可能平时用的不多 仅做参考 当然了 有更加简单的方式录制视频 但是并不好扩展 比如加滤镜效果等 还有一部分原因是为后面更好的学习视频编码。很多人在找IFonx之类的软件 应该8.0之后这个软件就不做更新了 那么怎么看我保存的文件 只要在 info.plist 文件加上一个 UIFileSharingEnabled 设置为YES, 然后打开电脑端的iTunes 连接 去看项目 就可以看到Document里面的文件了 然后将视频导出 看是否有错误 如果有错误看自己设置是不是有问题 如图所示
干货 代码如下