简体   繁体   English

摄像头打开时自动开始录像?

[英]Video recording start automatically when camera Open?

I have read lots of tutorials for video player.我已经阅读了很多视频播放器的教程。 But How to start recording when camera open in a custom view with time limit.但是如何在有时间限制的自定义视图中打开相机时开始录制。

Here is the working solution with a swift version这是快速版本的工作解决方案

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)
}


}

I have done same thing in java using Robot class on laptop.我在笔记本电脑上使用 Robot 类在 java 中做了同样的事情。 Robot class is capable of sending keystrokes and mouse movements automatically. Robot 类能够自动发送击键和鼠标移动。 You can try same thing on your platform.你可以在你的平台上尝试同样的事情。 Automate the button press event so that recording get started.自动化按钮按下事件,以便开始录制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM