video recording swiftui
时间: 2023-09-16 18:15:24 浏览: 117
In SwiftUI, you can use the `AVCaptureSession` and `AVCaptureVideoPreviewLayer` classes from the AVFoundation framework to record videos. Here's an example of how you can do it:
```swift
import SwiftUI
import AV
struct ContentView: View {
@State private var isRecording = false
let captureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var body: some View {
VStack {
if !isRecording {
Button("Record") {
startRecording()
}
} else {
Button("Stop") {
stopRecording()
}
}
}
.onAppear {
setupCamera()
}
}
func setupCamera() {
let captureDevice = AVCaptureDevice.default(for: .video)
guard let input = try? AVCaptureDeviceInput(device: captureDevice!) else { return }
guard captureSession.canAddInput(input) else { return }
captureSession.addInput(input)
guard captureSession.canAddOutput(movieOutput) else { return }
captureSession.sessionPreset = .high
captureSession.addOutput(movieOutput)
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.videoGravity = .resizeAspectFill
let rootLayer = NSView(frame: NSRect(x: 0, y: 0, width: 300, height: 300))
rootLayer.wantsLayer = true
rootLayer.layer?.backgroundColor = NSColor.black.cgColor
rootLayer.layer?.addSublayer(previewLayer)
previewLayer.frame = rootLayer.bounds
let uiView = NSHostingView(rootView: rootLayer)
uiView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
let viewController = NSViewController()
viewController.view = uiView
let window = NSWindow(contentViewController: viewController)
window.makeKeyAndOrderFront(nil)
captureSession.startRunning()
}
func startRecording() {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let fileUrl = paths[0].appendingPathComponent("output.mov")
movieOutput.startRecording(to: fileUrl, recordingDelegate: self)
isRecording = true
}
func stopRecording() {
movieOutput.stopRecording()
isRecording = false
}
}
extension ContentView: AVCaptureFileOutputRecordingDelegate {
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
print("Started recording to \(fileURL)")
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print("Finished recording to \(outputFileURL)")
}
}
```
This example sets up a camera preview using `AVCaptureVideoPreviewLayer` and records a video when the "Record" button is tapped. The recorded video is saved to the document directory with the name "output.mov". The recording can be stopped by tapping the "Stop" button.
Please note that this code is for macOS development using SwiftUI. If you want to record videos in SwiftUI for iOS, you will need to make some modifications.
阅读全文