相机打开时视频录制会自动开始吗?

时间:2016-03-18 07:57:39

标签: ios objective-c iphone

我已经阅读了很多关于视频播放器的教程。但是如何在具有时间限制的自定义视图中打开相机时开始录制。

2 个答案:

答案 0 :(得分:0)

这是快速版本的有效解决方案

var session: AVCaptureSession?
var userreponsevideoData = NSData()
var userreponsethumbimageData = NSData()

override func viewDidLoad() {
    super.viewDidLoad()
     createSession()
}

func for stopRecording(){
  session?.stopRunning()
}

func createSession() {

var input: AVCaptureDeviceInput?
let  movieFileOutput = AVCaptureMovieFileOutput()
videosPreviewLayer?.frame.size = photoPreviewImageView.frame.size
session = AVCaptureSession()
let error: NSError? = nil
do { input = try AVCaptureDeviceInput(device: self.cameraWithPosition(position: .back)!) } catch {return}
if error == nil {
    session?.addInput(input!)
} else {
    print("camera input error: \(String(describing: error))")
}
videosPreviewLayer = AVCaptureVideoPreviewLayer(session: session!)
videosPreviewLayer?.frame.size = self.photoPreviewImageView.frame.size
videosPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videosPreviewLayer?.connection?.videoOrientation = .portrait
photoPreviewImageView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
photoPreviewImageView.layer.addSublayer(videosPreviewLayer!)

switchCameraButton.isHidden=true
flashButton.isHidden=true
msgLabel.isHidden=true
galleryCollectionView.isHidden=true
timerLabel.isHidden=false

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
fileURL = URL(string:"\(documentsURL.appendingPathComponent("temp"))" + ".mov")
print("*****fileurl%@",fileURL ?? "00000")

let maxDuration: CMTime = CMTimeMake(600, 10)
movieFileOutput.maxRecordedDuration = maxDuration
movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024
if self.session!.canAddOutput(movieFileOutput) {
    self.session!.addOutput(movieFileOutput)
}
session?.startRunning()
movieFileOutput.startRecording(to: fileURL!, recordingDelegate: self)
}

func cameraWithPosition(position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let devices = AVCaptureDevice.devices(for: AVMediaType.video)
for device in devices {
    if device.position == position {
        return device
    }
}
return nil
}
}
extension SwipeGallerymainViewController: AVCaptureFileOutputRecordingDelegate
{

func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print(outputFileURL)
let filemainurl = outputFileURL

do
{
    let asset = AVURLAsset(url:filemainurl as URL, options:nil)
    print(asset)
    let imgGenerator = AVAssetImageGenerator(asset: asset)
    imgGenerator.appliesPreferredTrackTransform = true
    let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
    let uiImage = UIImage(cgImage: cgImage)
    previewImage = uiImage
    userreponsethumbimageData = NSData(contentsOf: filemainurl as URL)!
    print(userreponsethumbimageData.length)
    print(uiImage)

}
catch let error as NSError
{
    print(error)
    return
}
let VideoFilePath = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent("mergeVideo\(arc4random()%1000)d").appendingPathExtension("mp4").absoluteString
if FileManager.default.fileExists(atPath: VideoFilePath)
{
    print("exist")
    do
    {
        try FileManager.default.removeItem(atPath: VideoFilePath)
    }
    catch { }
}

let tempfilemainurl =  NSURL(string: VideoFilePath)!
let sourceAsset = AVURLAsset(url:filemainurl as URL, options:nil)
let assetExport: AVAssetExportSession = AVAssetExportSession(asset: sourceAsset, presetName: AVAssetExportPresetMediumQuality)!
assetExport.outputFileType = AVFileType.mov
assetExport.outputURL = tempfilemainurl as URL
assetExport.exportAsynchronously { () -> Void in
    switch assetExport.status
    {
    case AVAssetExportSessionStatus.completed:
        DispatchQueue.main.async {
            do
            {

                self.userreponsevideoData = try NSData(contentsOf: tempfilemainurl as URL, options: NSData.ReadingOptions())
                print("MB - \(self.userreponsevideoData.length) byte")
                self.isVideoLoad=true
                self.performSegue(withIdentifier:"previewSegue", sender:self)
            }
            catch
            {

                print(error)
            }
        }

    case  AVAssetExportSessionStatus.failed:
        print("failed \(String(describing: assetExport.error))")
    case AVAssetExportSessionStatus.cancelled:
        print("cancelled \(String(describing: assetExport.error))")
    default:
        print("complete")

    }

}
}

 func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
print(fileURL)
}


}

答案 1 :(得分:-1)

我在笔记本电脑上使用Robot类在java中做了同样的事情。机器人类能够自动发送击键和鼠标移动。您可以在平台上尝试相同的操作。自动按钮按下事件,以便开始录制。