2017-06-27 11 views
0

カスタムカメラをセットアップし、ビデオプレビューを既にコーディングしました。私はそれが押されたときにビデオをキャプチャするために使用したい画面上のボタンを持っています。私はそれについてどうやって行くのか分からない。これまでのことすべてがセットアップされ、うまく動作します。カスタムカメラを使用してビデオをキャプチャする方法

録画開始ボタン機能では、ビデオをキャプチャして保存するのに必要なコードが必要です。ありがとうございました

class CameraViewController: UIViewController, AVAudioRecorderDelegate { 

@IBOutlet var recordOutlet: UIButton! 


@IBOutlet var recordLabel: UILabel! 

@IBOutlet var cameraView: UIView! 
var tempImage: UIImageView? 

var captureSession: AVCaptureSession? 
var stillImageOutput: AVCapturePhotoOutput? 
var videoPreviewLayer: AVCaptureVideoPreviewLayer? 
var currentCaptureDevice: AVCaptureDevice? 

var usingFrontCamera = false 

/* This is the function i want to use to start 
recording a video */ 

@IBAction func recordingButton(_ sender: Any) { 



} 

答えて

1

アップルは開発者がビデオをキャプチャするためにデフォルトのカメラを使用するように思えます。あなたがそれで大丈夫なら、チュートリアルをオンラインで見つけて助けてください。 https://www.raywenderlich.com/94404/play-record-merge-videos-ios-swift

「ビデオを録画する」セクションまでスクロールすると、コードが表示されます。ここで

はそれが言っていることの一部だ: "

import MobileCoreServices 

あなたはまた、ファイルの末尾に以下を追加することで、PlayVideoViewControllerと同じプロトコルを採用する必要があります:

`extension RecordVideoViewController: UIImagePickerControllerDelegate { 

}

extension RecordVideoViewController: UINavigationControllerDelegate { }

はRecordVideoViewControllerに次のコードを追加します

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

このメソッドは、同じロジックがPlayVideoViewControllerであるが、それは記録映像に代わり.Cameraにアクセスし、次の。あなたはおなじみの領土に再びです

startCameraFromViewController(self, withDelegate: self) 

: は今レコード(_ :)に以下を追加します。このコードでは、「ビデオの録画」ボタンをタップすると、startCameraControllerFromViewController(_:usingDelegate:)が呼び出されます。

ビルドして実行して、これまでのものを確認してください。 録画画面に移動し、「ビデオ録画」ボタンを押します。フォトギャラリーの代わりに、カメラのUIが開きます。画面の下部にある赤い録音ボタンをタップして、ビデオの録画を開始し、あなたが記録し終わったら、再びそれをタップする。」

乾杯、 テオ

0

ここでは、コードに働いている、あなたが対処する必要があります実際のプロジェクトではoptionalの値とerrorの扱いで修正しますが、次のコードを例として使用できます。

// 
// ViewController.swift 
// CustomCamera 
// 
// Created by Taras Chernyshenko on 6/27/17. 
// Copyright © 2017 Taras Chernyshenko. All rights reserved. 
// 

import UIKit 
import AVFoundation 
import AssetsLibrary 

class CameraViewController: UIViewController, 
    AVCaptureAudioDataOutputSampleBufferDelegate, 
    AVCaptureVideoDataOutputSampleBufferDelegate { 

    @IBOutlet var recordOutlet: UIButton! 
    @IBOutlet var recordLabel: UILabel! 

    @IBOutlet var cameraView: UIView! 
    var tempImage: UIImageView? 

    private var session: AVCaptureSession = AVCaptureSession() 
    private var deviceInput: AVCaptureDeviceInput? 
    private var previewLayer: AVCaptureVideoPreviewLayer? 
    private var videoOutput: AVCaptureVideoDataOutput = AVCaptureVideoDataOutput() 
    private var audioOutput: AVCaptureAudioDataOutput = AVCaptureAudioDataOutput() 

    private var videoDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
    private var audioConnection: AVCaptureConnection? 
    private var videoConnection: AVCaptureConnection? 

    private var assetWriter: AVAssetWriter? 
    private var audioInput: AVAssetWriterInput? 
    private var videoInput: AVAssetWriterInput? 

    private var fileManager: FileManager = FileManager() 
    private var recordingURL: URL? 

    private var isCameraRecording: Bool = false 
    private var isRecordingSessionStarted: Bool = false 

    private var recordingQueue = DispatchQueue(label: "recording.queue") 
    var captureSession: AVCaptureSession? 
    var stillImageOutput: AVCapturePhotoOutput? 
    var videoPreviewLayer: AVCaptureVideoPreviewLayer? 
    var currentCaptureDevice: AVCaptureDevice? 

    var usingFrontCamera = false 

    /* This is the function i want to use to start 
    recording a video */ 

    @IBAction func recordingButton(_ sender: Any) { 
     if self.isCameraRecording { 
      self.stopRecording() 
     } else { 
      self.startRecording() 
     } 
     self.isCameraRecording = !self.isCameraRecording 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.setup() 
    } 

    private func setup() { 
     self.session.sessionPreset = AVCaptureSessionPresetHigh 

     self.recordingURL = URL(fileURLWithPath: "\(NSTemporaryDirectory() as String)/file.mov") 
     if self.fileManager.isDeletableFile(atPath: self.recordingURL!.path) { 
      _ = try? self.fileManager.removeItem(atPath: self.recordingURL!.path) 
     } 

     self.assetWriter = try? AVAssetWriter(outputURL: self.recordingURL!, 
      fileType: AVFileTypeQuickTimeMovie) 

     let audioSettings = [ 
      AVFormatIDKey : kAudioFormatAppleIMA4, 
      AVNumberOfChannelsKey : 1, 
      AVSampleRateKey : 16000.0 
     ] as [String : Any] 

     let videoSettings = [ 
      AVVideoCodecKey : AVVideoCodecH264, 
      AVVideoWidthKey : UIScreen.main.bounds.size.width, 
      AVVideoHeightKey : UIScreen.main.bounds.size.height 
     ] as [String : Any] 

     self.videoInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, 
      outputSettings: videoSettings) 
     self.audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, 
      outputSettings: audioSettings) 

     self.videoInput?.expectsMediaDataInRealTime = true 
     self.audioInput?.expectsMediaDataInRealTime = true 

     if self.assetWriter!.canAdd(self.videoInput!) { 
      self.assetWriter?.add(self.videoInput!) 
     } 

     if self.assetWriter!.canAdd(self.audioInput!) { 
      self.assetWriter?.add(self.audioInput!) 
     } 

     self.deviceInput = try? AVCaptureDeviceInput(device: self.videoDevice) 

     if self.session.canAddInput(self.deviceInput) { 
      self.session.addInput(self.deviceInput) 
     } 

     self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session) 
     self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect 

     let rootLayer = self.view.layer 
     rootLayer.masksToBounds = true 
     self.previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) 

     rootLayer.insertSublayer(self.previewLayer!, at: 0) 

     self.session.startRunning() 

     DispatchQueue.main.async { 
      self.session.beginConfiguration() 

      if self.session.canAddOutput(self.videoOutput) { 
       self.session.addOutput(self.videoOutput) 
      } 

      self.videoConnection = self.videoOutput.connection(withMediaType: AVMediaTypeVideo) 
      if self.videoConnection?.isVideoStabilizationSupported == true { 
       self.videoConnection?.preferredVideoStabilizationMode = .auto 
      } 
      self.session.commitConfiguration() 

      let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio) 
      let audioIn = try? AVCaptureDeviceInput(device: audioDevice) 

      if self.session.canAddInput(audioIn) { 
       self.session.addInput(audioIn) 
      } 

      if self.session.canAddOutput(self.audioOutput) { 
       self.session.addOutput(self.audioOutput) 
      } 

      self.audioConnection = self.audioOutput.connection(withMediaType: AVMediaTypeAudio) 
     } 
    } 

    private func startRecording() { 
     if self.assetWriter?.startWriting() != true { 
      print("error: \(self.assetWriter?.error.debugDescription ?? "")") 
     } 

     self.videoOutput.setSampleBufferDelegate(self, queue: self.recordingQueue) 
     self.audioOutput.setSampleBufferDelegate(self, queue: self.recordingQueue) 
    } 

    private func stopRecording() { 
     self.videoOutput.setSampleBufferDelegate(nil, queue: nil) 
     self.audioOutput.setSampleBufferDelegate(nil, queue: nil) 

     self.assetWriter?.finishWriting { 
      print("saved") 
     } 
    } 
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer 
     sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!) { 

     if !self.isRecordingSessionStarted { 
      let presentationTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) 
      self.assetWriter?.startSession(atSourceTime: presentationTime) 
      self.isRecordingSessionStarted = true 
     } 

     let description = CMSampleBufferGetFormatDescription(sampleBuffer)! 

     if CMFormatDescriptionGetMediaType(description) == kCMMediaType_Audio { 
      if self.audioInput!.isReadyForMoreMediaData { 
       print("appendSampleBuffer audio"); 
       self.audioInput?.append(sampleBuffer) 
      } 
     } else { 
      if self.videoInput!.isReadyForMoreMediaData { 
       print("appendSampleBuffer video"); 
       if !self.videoInput!.append(sampleBuffer) { 
        print("Error writing video buffer"); 
       } 
      } 
     } 
    } 
} 
関連する問題