我正在尝试在 Swift 中创建自定义相机。我发现了很多关于这个的帖子,并设法打开了相机,有一个“开始录制”按钮。但是,当单击“开始录制”按钮时,出现此错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureMovieFileOutput startRecordingToOutputFileURL:recordingDelegate:] No active/enabled connections'
查到这个错误,应该是我在beginSession函数中没有设置相机画质导致的:
func beginSession(captureDevice: AVCaptureDevice) {
var err : NSError? = nil
var input = AVCaptureDeviceInput?()
do {
input = try AVCaptureDeviceInput(device: captureDevice)
} catch _ {
//Error handling, if needed
}
captureSession.addInput(input)
captureSession.sessionPreset = AVCaptureSessionPresetHigh;
if err != nil {
print("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer!)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()
let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70))
btn.backgroundColor = hexStringToUIColor("#E53935")
btn.setTitle("Start Recording", forState: UIControlState.Normal)
btn.addTarget(self, action: "takeVideoAction", forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1 // change tag property
self.view.addSubview(btn)
}
完整代码如下:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate,AVCaptureFileOutputRecordingDelegate {
let imagePicker: UIImagePickerController! = UIImagePickerController()
let saveFileName = "/test.mp4"
var locationManager : CLLocationManager! = CLLocationManager()
var startLocation: CLLocation!
//let captureSession = AVCaptureSession()
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
let captureSession = AVCaptureSession()
// MARK: ViewController methods
override func viewDidLoad() {
super.viewDidLoad()
//var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a nib.
let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70))
btn.backgroundColor = hexStringToUIColor("#E53935")
btn.setTitle("Go to recording", forState: UIControlState.Normal)
btn.addTarget(self, action: "recordVideo:", forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1 // change tag property
self.view.addSubview(btn) // add to view as subview
if CLLocationManager.locationServicesEnabled() {
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
print(locationManager.location)
}
}
func startCameraFromViewController(viewController: UIViewController, withDelegate delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>) -> Bool {
if UIImagePickerController.isSourceTypeAvailable(.Camera) == false {
return false
}
var cameraController = UIImagePickerController()
cameraController.sourceType = .Camera
cameraController.mediaTypes = [kUTTypeMovie as NSString as String]
cameraController.allowsEditing = false
cameraController.delegate = delegate
presentViewController(cameraController, animated: true, completion: nil)
return true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
dismissViewControllerAnimated(true, completion: nil)
// Handle a movie capture
if mediaType == kUTTypeMovie {
guard let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path else { return }
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) {
UISaveVideoAtPathToSavedPhotosAlbum(path, self, #selector(ViewController.video(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
}
func video(videoPath: NSString, didFinishSavingWithError error: NSError?, contextInfo info: AnyObject) {
var title = "Success"
var message = "Video was saved"
if let _ = error {
title = "Error"
message = "Video failed to save"
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
// MARK: Button handlers
// Record a video
@IBAction func recordVideo(sender: AnyObject) {
let devices = AVCaptureDevice.devices()
captureSession.sessionPreset = AVCaptureSessionPresetHigh
// captureSession.sessionPreset = kCaptureSessionPresetVideo
for device in devices {
// Make sure this particular device supports video
if (device.hasMediaType(AVMediaTypeVideo)) {
// Finally check the position and confirm we've got the back camera
if(device.position == AVCaptureDevicePosition.Back) {
var captureDevice = device as? AVCaptureDevice
if captureDevice != nil {
beginSession(captureDevice!)
}
}
}
}
}
func beginSession(captureDevice: AVCaptureDevice) {
var err : NSError? = nil
var input = AVCaptureDeviceInput?()
do {
input = try AVCaptureDeviceInput(device: captureDevice)
} catch _ {
//Error handling, if needed
}
captureSession.addInput(input)
captureSession.sessionPreset = AVCaptureSessionPresetHigh;
if err != nil {
print("error: \(err?.localizedDescription)")
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer!)
previewLayer?.frame = self.view.layer.frame
captureSession.startRunning()
let btn: UIButton = UIButton(frame: CGRectMake((self.view.frame.size.width-350)/2, (self.view.frame.size.height-80), 350, 70))
btn.backgroundColor = hexStringToUIColor("#E53935")
btn.setTitle("Start Recording", forState: UIControlState.Normal)
btn.addTarget(self, action: "takeVideoAction", forControlEvents: UIControlEvents.TouchUpInside)
btn.tag = 1 // change tag property
self.view.addSubview(btn)
}
func takeVideoAction() {
var fileName = "mysavefile.mp4";
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
var filePath = documentsURL.URLByAppendingPathComponent(fileName)
let videoFileOutput = AVCaptureMovieFileOutput()
let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self
videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)
self.captureSession.addOutput(videoFileOutput)
startCameraFromViewController(self, withDelegate: self)
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
return
}
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
return
}
}
任何输入将不胜感激
最佳答案
您需要在调用 startRecordingToOutputFileURL 之前将视频文件输出添加到捕获 session :
self.captureSession.addOutput(videoFileOutput)
videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)
关于swift - AVFoundation:开始记录由于 "No active/enabled connection"而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39953945/
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少
Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa