我试图通过AVAssetWriter录制视频。 NSData成功写入我指定的文件路径并作为AVAsset提取,但它似乎是仅表示记录的1帧的数据,而不是作为视频附加在一起的多个帧。当我尝试在UI中播放视频时,它会立即完成。并且NSData对象的大小远小于视频的预期。是什么让我觉得它只追加1帧。 这是我的代码:
func setupCaptureSession() {
self.session = AVCaptureSession()
session!.sessionPreset = AVCaptureSessionPresetMedium
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: device)
session!.addInput(input)
} catch {
}
let captureLayer = AVCaptureVideoPreviewLayer(session: session)
captureLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
let window = UIApplication.sharedApplication().keyWindow!
let layerRect = window.layer.bounds
captureLayer.bounds = layerRect
captureLayer.position = CGPointMake(CGRectGetMidX(layerRect), CGRectGetMidY(layerRect))
self.cameraView = NSBundle.mainBundle().loadNibNamed("CameraView", owner: self, options: nil)[0] as? CameraView
cameraView!.frame = layerRect
cameraView!.layer.insertSublayer(captureLayer, atIndex: 0)
window.addSubview(cameraView!)
let output = AVCaptureVideoDataOutput()
session!.addOutput(output)
let queue = dispatch_queue_create("myQueue", nil)
output.setSampleBufferDelegate(self, queue: queue)
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey: NSNumber(unsignedInt: kCVPixelFormatType_32BGRA)]
output.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = .Portrait
session!.startRunning()
}
示例缓冲区委托:
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
if self.recording == true {
let window = UIApplication.sharedApplication().keyWindow!
if let path = Utils.documentDirectory().URLByAppendingPathComponent("temp_video").path {
print("recording")
self.videoFromBuffer(sampleBuffer, path: path, size: window.frame.size, duration: self.duration)
}
}
}
AVAssetWriter:
private func videoFromBuffer(buffer: CMSampleBuffer, path: String, size: CGSize, duration: Int64) {
do {
let writer = try AVAssetWriter(URL: NSURL(fileURLWithPath: path), fileType: AVFileTypeMPEG4)
let settings = [AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: NSNumber(integer: Int(size.width)),
AVVideoHeightKey: NSNumber(integer: Int(size.height))]
let writerInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: settings)
writerInput.expectsMediaDataInRealTime = true
writer.addInput(writerInput)
writer.startWriting()
writer.startSessionAtSourceTime(kCMTimeZero)
writerInput.appendSampleBuffer(buffer)
writerInput.markAsFinished()
writer.endSessionAtSourceTime(CMTimeMake(duration, 1))
writer.finishWritingWithCompletionHandler({ () -> Void in
})
} catch {
print(error)
}
}
为什么结果数据不是完整视频?