在使用AVCaptureSession进行流式传输实时预览视频并拍照后返回流式传输时,可以按照以下步骤进行操作:
let captureSession = AVCaptureSession()
let videoDevice = AVCaptureDevice.default(for: .video)
let videoInput = try AVCaptureDeviceInput(device: videoDevice!)
let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "sample buffer delegate"))
captureSession.addInput(videoInput)
captureSession.addOutput(videoOutput)
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = view.bounds
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// 获取帧数据
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
// 将帧数据转换为图片
let ciImage = CIImage(cvImageBuffer: imageBuffer!)
let image = UIImage(ciImage: ciImage)
// 将图片显示在预览视图上
previewLayer.contents = image?.cgImage
}
func takePhoto() {
let videoConnection = videoOutput.connection(with: .video)
videoOutput.captureStillImageAsynchronously(from: videoConnection!) { (buffer, error) in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer!)
let image = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}
}
captureSession.stopRunning()
previewLayer.removeFromSuperlayer()
captureSession.removeInput(videoInput)
captureSession.removeOutput(videoOutput)
这样就可以实现使用AVCaptureSession进行流式传输实时预览视频并拍照后返回流式传输的功能。
领取专属 10元无门槛券
手把手带您无忧上云