在iOS设备上切换摄像头可以通过AVCaptureDevice类和AVCaptureSession类来实现。以下是一个简单的示例代码:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var captureSession: AVCaptureSession?
var currentCamera: AVCaptureDevice?
var currentCameraInput: AVCaptureDeviceInput?
var previewLayer: AVCaptureVideoPreviewLayer?
override func viewDidLoad() {
super.viewDidLoad()
setupCaptureSession()
setupPreviewLayer()
startCaptureSession()
}
func setupCaptureSession() {
captureSession = AVCaptureSession()
captureSession?.sessionPreset = .photo
guard let availableDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified).devices else { return }
for device in availableDevices {
if device.position == .back {
currentCamera = device
break
}
}
do {
currentCameraInput = try AVCaptureDeviceInput(device: currentCamera!)
captureSession?.addInput(currentCameraInput!)
} catch {
print(error.localizedDescription)
}
}
func setupPreviewLayer() {
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
previewLayer?.videoGravity = .resizeAspectFill
previewLayer?.frame = view.bounds
view.layer.insertSublayer(previewLayer!, at: 0)
}
func startCaptureSession() {
captureSession?.startRunning()
}
func switchCamera() {
captureSession?.beginConfiguration()
guard let newCameraInput = try? AVCaptureDeviceInput(device: getOppositeCamera()) else { return }
captureSession?.removeInput(currentCameraInput!)
if captureSession?.canAddInput(newCameraInput) ?? false {
captureSession?.addInput(newCameraInput)
currentCameraInput = newCameraInput
} else {
captureSession?.addInput(currentCameraInput!)
}
captureSession?.commitConfiguration()
}
func getOppositeCamera() -> AVCaptureDevice? {
if currentCamera?.position == .back {
return AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .front).devices.first
} else {
return AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back).devices.first
}
}
@IBAction func switchCameraButtonTapped(_ sender: UIButton) {
switchCamera()
}
}
这段代码使用AVCaptureSession来设置摄像头会话,并使用AVCaptureDeviceInput将摄像头添加到会话中。然后,使用AVCaptureVideoPreviewLayer将摄像头预览图层添加到视图中。最后,通过切换输入设备来切换摄像头。
请注意,这只是一个简单的示例代码,实际应用中可能需要处理更多的错误和异常情况。此外,还可以根据需要添加其他功能,如拍照、录制视频等。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云