我希望在iPhone的显示屏上看到240 fps的视频预览。 我的代码(简称)就像这样(以下):进行会话,激活相机并在显示屏上显示实际的视频预览。
var session: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
override func viewDidLoad() {
super.viewDidLoad()
super.viewWillAppear(true)
session = AVCaptureSession()
let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var error: NSError?
var input: AVCaptureDeviceInput!
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let errorgesehen as NSError {
error = errorgesehen
input = nil
print(error!.localizedDescription)
}
configureCameraForHighestFrameRate(device: backCamera!)
if error == nil && session!.canAddInput(input) {
session!.addInput(input)
}
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
videoPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
videoPreviewLayer!.frame = CGRect(x: 0.0, y: 0.0, width: view.bounds.size.width, height: view.bounds.size.height)
videoPreviewLayer!.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 1).cgColor
view.layer.addSublayer(videoPreviewLayer!)
session?.startRunning()
UIApplication.shared.isIdleTimerDisabled = true
}
现在我希望这个视频预览以240fps显示(60或120也可以,但240是最好的)。为了解决这个问题,我使用了这个:https://developer.apple.com/documentation/avfoundation/avcapturedevice(我把它变成了Swift)。函数configureCameraForHighestFrameRate
具有以下代码:
func configureCameraForHighestFrameRate(device: AVCaptureDevice) {
var bestFormat: AVCaptureDeviceFormat? = nil
var bestFrameRateRange: AVFrameRateRange? = nil
for formatf in device.formats {
var format = formatf as! AVCaptureDeviceFormat
print(format)
for rangef in format.videoSupportedFrameRateRanges {
var range = rangef as! AVFrameRateRange
print(range)
if (bestFrameRateRange == nil) {
bestFormat = format
bestFrameRateRange = range
} else if range.maxFrameRate > bestFrameRateRange!.maxFrameRate {
bestFormat = format
bestFrameRateRange = range
}
}
}
if (bestFormat == nil) {
print("Es gibt keine Formate, die Apokalypse ist ausgebrochen.")
return;
} else if (bestFrameRateRange == nil) {
print("Es gibt keine Bilder, die Apokalypse ist ausgebrochen.")
return;
}
let Richtig = bestFormat!
let fps = bestFrameRateRange!
do {
try device.lockForConfiguration()
}
catch let error as NSError {
print(error.description)
}
device.activeFormat = Richtig
device.activeVideoMinFrameDuration = fps.minFrameDuration
device.activeVideoMaxFrameDuration = fps.minFrameDuration
device.unlockForConfiguration()
}
此代码查找AVCaptureDeviceFormat,其中fps编号为maximal(= 240)。实际格式设置为此格式,并将fps数设置为最大值(= 240)。 但我有一个问题,即视频输出仍然只包含每个框架30帧(如果我很快转动iPhone,我会认出它)。 另外,有几种格式,其中最大fps是240.这个代码只选择了第一个,但我问我是否存在差异以及选择哪个以获得最佳输出。任何人都可以说几种形式的差异或者哪种格式,“相机”应用程序在慢动作工具中使用?非常感谢你 :)
在将格式配置设置为AVCaptureSession
之前,您应该启动AVCaptureDevice