1 自定義攝像頭
AVFoundation
要想熟悉OC里面的框架 理解這個(gè)框架結(jié)構(gòu)圖必不可少 不過(guò)這是我盜過(guò)來(lái)的圖 嘿嘿嘿 這是 AVFoundation 框架圖

Paste_Image.png
AVAudioToolBox
VideoToolBox
AVCaptureDevice
AVCaptureDeviceInput
AVCaptureSession
AVCaptureVideoPreviewLayer
// 輸入設(shè)備
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 {
// 輸入設(shè)備
let cameraDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let inputDevice = try AVCaptureDeviceInput(device: cameraDevice)
// 輸出設(shè)備
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()
//設(shè)置分辨率
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!) {
}
}
項(xiàng)目中可能會(huì)報(bào)這樣的錯(cuò)誤

Paste_Image.png
也不用慌張這是因?yàn)镮OS在8.0之后加了視頻 音頻等設(shè)備的訪問(wèn)權(quán)限 在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>
獲取的視頻源會(huì)通過(guò)AVCaptureVideoDataOutputSampleBufferDelegate 代理生成
CMSampleBuffer 在這里我們可以通過(guò) CMSampleBuffer實(shí)現(xiàn)視頻截圖功能這個(gè)功能可以自行百度這里不做展開 下一章介紹 CMSampleBuffer
附錄 1 錄制視頻功能以及保存
這部分的功能可能平時(shí)用的不多 僅做參考 當(dāng)然了 有更加簡(jiǎn)單的方式錄制視頻 但是并不好擴(kuò)展 比如加濾鏡效果等 還有一部分原因是為后面更好的學(xué)習(xí)視頻編碼。很多人在找IFonx之類的軟件 應(yīng)該8.0之后這個(gè)軟件就不做更新了 那么怎么看我保存的文件 只要在 info.plist 文件加上一個(gè) UIFileSharingEnabled 設(shè)置為YES, 然后打開電腦端的iTunes 連接 去看項(xiàng)目 就可以看到Document里面的文件了 然后將視頻導(dǎo)出 看是否有錯(cuò)誤 如果有錯(cuò)誤看自己設(shè)置是不是有問(wèn)題 如圖所示

Paste_Image.png
干貨 代碼如下