2014-10-04 60 views
15

我已經設法編寫一些代碼來打開相機並預覽視頻。我現在想捕捉從輸出幀發送到理想的編碼爲H.264從Swift中的AVCaptureSession獲取輸出以發送到服務器

這裏的服務器是我得到了什麼:

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    let captureSession = AVCaptureSession() 
    var previewLayer : AVCaptureVideoPreviewLayer? 

    // If we find a device we'll store it here for later use 
    var captureDevice : AVCaptureDevice? 

    override func viewDidLoad() { 
     super.viewDidLoad()    
     // Do any additional setup after loading the view, typically from a nib. 

     captureSession.sessionPreset = AVCaptureSessionPresetHigh 

     let devices = AVCaptureDevice.devices() 

     // Loop through all the capture devices on this phone 
     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) { 
        captureDevice = device as? AVCaptureDevice 
        if captureDevice != nil { 
         println("Capture device found") 
         beginSession() 
        } 
       } 
      } 
     } 

    } 

    func beginSession() { 

     var err : NSError? = nil 
     captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err)) 

     if err != nil { 
      println("error: \(err?.localizedDescription)") 
     } 

     previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     self.view.layer.addSublayer(previewLayer) 
     previewLayer?.frame = self.view.layer.frame 

     captureSession.startRunning() 

    } 

} 

這種開放式的相機成功,我可以預覽鏡頭。

我發現這個Objective C代碼看起來像它得到的輸出,但我不知道如何將其轉換爲swift。它使用AVCaptureVideoDataOutput,AVAssetWriter,AVAssetWriterInput和AVAssetWriterInputPixelBufferAdaptor將幀寫入H.264編碼的電影文件。

Can use AVCaptureVideoDataOutput and AVCaptureMovieFileOutput at the same time?

有人可以幫助轉換,或給我指針,以如何獲得幀離開我當前的代碼?

+0

這些東西的文檔缺乏迅速。這非常令人沮喪。 – 2015-02-19 16:10:06

+0

您是否找到解決方案? – 2015-05-08 09:13:40

+0

你想轉換代碼[可以同時使用AVCaptureVideoDataOutput和AVCaptureMovieFileOutput?](http://stackoverflow.com/questions/4944083/can-use-avcapturevideodataoutput-and-avcapturemoviefileoutput-at-the-same-time )迅速? – 2015-05-09 15:20:10

回答

3

Apple在ObjectiveC中有一個示例項目AVCam,可以處理這些事情。

Here's關於在Swift中使用AVCamera的SO的另一個問題。

我個人使用這個https://github.com/alex-chan/AVCamSwift,這很好。我只需要將它轉換爲Xcode中的最新Swift語法,並且它工作正常。

另一個建議是使用您找到的ObjectiveC代碼,並通過橋接頭將其導入Swift代碼中。