gpt4 book ai didi

ios - 无法弄清楚为什么 VideoDeviceInput 没有被添加到我的 AVCaptureSession

转载 作者:行者123 更新时间:2023-11-28 07:07:43 24 4
gpt4 key购买 nike

一切正常。输出已正确添加,一切都已正确初始化,相机弹出等。唯一不起作用的是将视频设备作为输入添加到捕获 session 或此相机中,我无法理解为什么会发生这种情况。

也许不同的眼睛可以捕捉到这里发生的事情。如果有人可以看一下,我将不胜感激?

import UIKit
import Foundation
import AVFoundation


class CameraViewController: UIViewController {

@IBOutlet var recordingImage: UIImageView!
@IBOutlet var captureButton: UIButton!
@IBOutlet var flipCameraButton: UIButton!
@IBOutlet var switchCaptureButton: UIButton!
@IBOutlet weak var cameraView: UIView!

let cameraCapturePosition: AVCaptureDevicePosition = AVCaptureDevicePosition.Back
let session: AVCaptureSession = AVCaptureSession()
let totalTime: Float64 = 1800 // total time in seconds
let preferredTimeScale: Int32 = 45 // 45 FPS
let minFreeSpace: Int64 = 65999999 // minimum free disk space

var dataObject: AnyObject?
var cameraCaptureDevice: AVCaptureDevice?
var audioCaptureDevice: AVCaptureDevice?
var movieFileOutput: AVCaptureMovieFileOutput?
var stillImageOutput: AVCaptureStillImageOutput?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var captureConnection: AVCaptureConnection?
var weAreRecording: Bool = false
var beenHereBefore: Bool = false
var devicesSet: Bool = false

//**************** VIEW DID LOAD *****************
override func viewDidLoad() {

super.viewDidLoad()

registerRuntimeError()
registerDeviceConnections()
setSessionPreset()
}

//**************** VIEW DID APPEAR *****************
override func viewDidAppear(animated: Bool) {

//------INITIALIZE THE CAMERA------
if (!self.beenHereBefore) {
addInputs()
addOutputs()
setCameraOutputProperties()
startSession()
self.beenHereBefore = true
}
else {
println("Been Here Before")
}

self.weAreRecording = false
}

//**************** DID RECEIVE MEMORY WARNING *****************
override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

//**************** TAKES A PHOTO OR VIDEO *****************
@IBAction func didPressCapture(sender: AnyObject) {


}

//**************** SWITCHES THE CAPTURE MODES OF THE CAMERA ****************
@IBAction func didPressSwitchCapture(sender: AnyObject) {
//
// ----------- TODO ------------
//
}

//**************** FLIPS THE CAMERA BACK AND FORTH ****************
@IBAction func didPressFlipCamera(sender: AnyObject) {
//
// ----------- TODO ------------
//
}


//**************** INITIALIZE THE VIDEO CAPTURE SESSION ****************
func setSessionPreset() {

println("initializing video capture session")

//----- SET THE IMAGE QUALITY / RESOLUTION -----
//Options:
// AVCaptureSessionPresetHigh - Highest recording quality (varies per device)
// AVCaptureSessionPresetMedium - Suitable for WiFi sharing (actual values may change)
// AVCaptureSessionPresetLow - Suitable for 3G sharing (actual values may change)
// AVCaptureSessionPreset640x480 - 640x480 VGA (check its supported before setting it)
// AVCaptureSessionPreset1280x720 - 1280x720 720p HD (check its supported before setting it)
// AVCaptureSessionPresetPhoto - Full photo resolution (not supported for video output)
if session.canSetSessionPreset(AVCaptureSessionPresetHigh) {
println("Capture Session preset is set to High Quality")
session.sessionPreset = AVCaptureSessionPresetHigh
}
else {
//------IF FAILED, SET DEFAULT PRESET TO MEDIUM------
println("Capture Session preset is set to Medium Quality")
session.sessionPreset = AVCaptureSessionPresetMedium
}
}

//**************** ADD CAPTURE SESSION INPUTS ****************
func addInputs() {

println("Getting array of available capture devices")

//------GRAB ALL OF THE DEVICES------
let devices = AVCaptureDevice.devices()

//------FIND THE CAMERA MATCHING THE POSITION------
for device in devices {
if device.position == self.cameraCapturePosition {
self.cameraCaptureDevice = device as? AVCaptureDevice
println("Back camera has been added")
}
}

var error1: NSError? = nil
let videoDeviceInput = AVCaptureDeviceInput(device: self.cameraCaptureDevice, error: &error1)

//------PRINT ERROR IF ONE OCCURS------
if error1 != nil {
println("Error1 ---: \(error1?.description)")
}

//------ADD VIDEO AND AUDIO INPUT------
println("Trying to add video input")
if self.cameraCaptureDevice != nil {
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
println("Successfully added video input")
self.devicesSet = true
}
else {
// !!!!!!!!------- VIDEO INPUT IS NOT BEING ADDED TO THE SESSION -----------!!!!!!!!!!!
println("Could not add video input")
}
}
else {
println("Could not create video device")
}
}

//**************** ADD CAPTURE SESSION OUTPUTS ****************
func addOutputs() {

//------SET JPEG OUTPUT------
println("Setting JPEG Output")
self.stillImageOutput = AVCaptureStillImageOutput()
let outputSettings = [ AVVideoCodecKey : AVVideoCodecJPEG ]
self.stillImageOutput!.outputSettings = outputSettings
println("Successfully configured JPEG Ouput")

//------SET MOVIE FILE OUPUT MAX DURATION------
println("Setting Movie File Max Duration")
self.movieFileOutput = AVCaptureMovieFileOutput()
let maxDuration:CMTime = CMTimeMakeWithSeconds(self.totalTime, self.preferredTimeScale)
self.movieFileOutput!.maxRecordedDuration = maxDuration
println("Successully set movie file max duration")
println("Setting movie file minimun byte space")
self.movieFileOutput!.minFreeDiskSpaceLimit = self.minFreeSpace
println("Successfully added minium free space")


//------ADD JPEG OUTPUT AND MOVIE FILE OUTPUT TO SESSION OUTPUT------
println("Adding still image and movie file output")
if self.session.canAddOutput(self.stillImageOutput) && self.session.canAddOutput(self.movieFileOutput) {
self.session.addOutput(self.stillImageOutput)
self.session.addOutput(self.movieFileOutput)
println("Successfully added still image and movie file outputs")
}
else {
println("Could Not Add still image and movie file output")
}
}

//***************** SET ANY CAMERA PROPERTIES HERE ****************
func setCameraOutputProperties () {

//------INIT CAPTURE CONNECTION------
println("initializing the capture connection")
self.captureConnection = self.movieFileOutput!.connectionWithMediaType(AVMediaTypeVideo)
println("Capture Connection succesfully initialized")
}

//***************** REGISTER FOR RUNTIME NOTIFICATIONS ****************
func registerRuntimeError() {

println("Registering for runtime errors")
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didHaveRuntimeError"), name: AVCaptureSessionRuntimeErrorNotification, object: self.session)
}

//**************** REGISTER FOR DEVICE CONNECTION NOTIFICATIONS *****************
func registerDeviceConnections() {

println("Registering for connection notifications")
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("deviceConnected"), name: AVCaptureDeviceWasConnectedNotification, object: self.session)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("deviceDisconnected"), name: AVCaptureDeviceWasDisconnectedNotification, object: self.session)
}

//**************** START THE CAPTURE SESSION ****************
func startSession() {

println("About to add session inputs...")
addInputs()
println("Start configuring the capture")

//------CONFIG CAPTURE SESSION------
if !session.running {

println("Displaying camera in UI")

//------DISPLAY CAMERA IN UI------
self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
println("Video Preview Layer set")
self.cameraView.layer.addSublayer(self.videoPreviewLayer)
println("Video Preview Layer Added as sublayer")
self.videoPreviewLayer!.frame = self.cameraView.layer.frame
println("Video Preview frame set")
self.videoPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
println("Camera successully can display")

//------START CAMERA------
self.session.startRunning()
println("Capture Session initiated")
}
else {
println("Session is already running, no need to start it again")
}
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/

}

最佳答案

我觉得你错过了

AVCaptureFileOutputRecordingDelegate

你的错误打印出来了吗? :

println("Could not add video input")

println("Could not create video device")

关于ios - 无法弄清楚为什么 VideoDeviceInput 没有被添加到我的 AVCaptureSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com