You need to enable JavaScript to run this app. SwiftUI点击按钮触发后置摄像头视频录制功能实现求教
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI点击按钮触发后置摄像头视频录制功能实现求教

实现方案

以下是针对你需求的修改方案,可实现点击按钮启动录制、调用后置摄像头的功能:

核心修改点

  • 调整默认摄像头配置为后置
  • 移除页面加载自动启动录制的逻辑
  • 实现录制状态绑定监听,通过按钮控制录制启停
  • 调整倒计时逻辑与录制状态绑定,仅录制期间生效

修改后的完整代码

import SwiftUI
import AVKit

struct RecordingView: View {
    @State private var timer = 30
    @State private var onComplete = false
    @State private var recording = false
    
    var body: some View {
        ZStack {
            VideoRecordingView(timeLeft: $timer, onComplete: $onComplete, recording: $recording)
            VStack {
                Spacer()
                Button(action: {
                    recording.toggle()
                }, label: {
                    ZStack {
                        Circle()
                            .fill(recording ? .red : .white)
                            .frame(width: 65, height: 65)
                        
                        Circle()
                            .stroke(Color.white,lineWidth: 2)
                            .frame(width: 75, height: 75)
                    }
                })
                .padding(.bottom, 30)
            }
        }
        .ignoresSafeArea()
    }
}

以上是RecordingView的实现代码,额外优化了按钮样式,录制中按钮显示为红色更符合使用习惯

struct VideoRecordingView: UIViewRepresentable {
    @Binding var timeLeft: Int
    @Binding var onComplete: Bool
    @Binding var recording: Bool
    
    func makeUIView(context: Context) -> PreviewView {
        let recordingView = PreviewView()
        recordingView.onComplete = {
            self.onComplete = true
            self.recording = false
        }
        
        recordingView.onRecord = { timeLeft, totalShakes in
            self.timeLeft = timeLeft
        }
        
        recordingView.onReset = {
            self.recording = false
            self.timeLeft = 30
        }
        return recordingView
    }
    
    // 新增:监听录制状态变化,控制启停
    func updateUIView(_ uiView: PreviewView, context: Context) {
        if recording && !uiView.videoFileOutput.isRecording {
            uiView.startRecording()
        } else if !recording && uiView.videoFileOutput.isRecording {
            uiView.stopRecording()
            uiView.onReset?()
        }
    }
}

extension PreviewView: AVCaptureFileOutputRecordingDelegate{
    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
        if let error = error {
            print("录制出错:\(error.localizedDescription)")
            return
        }
        print("录制完成,文件路径:\(outputFileURL.absoluteString)")
    }
}

class PreviewView: UIView {
    private var captureSession: AVCaptureSession?
    private var shakeCountDown: Timer?
    let videoFileOutput = AVCaptureMovieFileOutput()
    var recordingDelegate:AVCaptureFileOutputRecordingDelegate!
    var recorded = 0
    var secondsToReachGoal = 30
    
    var onRecord: ((Int, Int)->())?
    var onReset: (() -> ())?
    var onComplete: (() -> ())?
    
    init() {
        super.init(frame: .zero)
        
        var allowedAccess = false
        let blocker = DispatchGroup()
        blocker.enter()
        AVCaptureDevice.requestAccess(for: .video) { flag in
            allowedAccess = flag
            blocker.leave()
        }
        blocker.wait()
        
        if !allowedAccess {
            print("!!! 无摄像头访问权限")
            return
        }
        
        // setup session
        let session = AVCaptureSession()
        session.beginConfiguration()
        
        // 修改:切换为后置摄像头
        let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
                                                  for: .video, position: .back)
        guard let videoDevice = videoDevice, let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice), session.canAddInput(videoDeviceInput) else {
            print("!!! 未检测到可用摄像头")
            return
        }
        session.addInput(videoDeviceInput)
        
        // 添加音频输入,录制带声音的视频
        if let audioDevice = AVCaptureDevice.default(for: .audio),
           let audioInput = try? AVCaptureDeviceInput(device: audioDevice),
           session.canAddInput(audioInput) {
            session.addInput(audioInput)
        }
        
        session.commitConfiguration()
        self.captureSession = session
    }
    
    override class var layerClass: AnyClass {
        AVCaptureVideoPreviewLayer.self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        return layer as! AVCaptureVideoPreviewLayer
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        recordingDelegate = self
        if nil != self.superview {
            self.videoPreviewLayer.session = self.captureSession
            self.videoPreviewLayer.videoGravity = .resizeAspectFill
            // 仅启动摄像头预览,不自动录制
            self.captureSession?.startRunning()
        } else {
            self.captureSession?.stopRunning()
        }
    }
    
    private func onTimerFires(){
        print("🟢 录制中,剩余时长:\(secondsToReachGoal)秒")
        secondsToReachGoal -= 1
        recorded += 1
        onRecord?(secondsToReachGoal, recorded)
        
        if(secondsToReachGoal == 0){
            stopRecording()
            shakeCountDown?.invalidate()
            shakeCountDown = nil
            onComplete?()
        }
    }
    
    func startTimers(){
        if shakeCountDown == nil {
            shakeCountDown = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] (timer) in
                self?.onTimerFires()
            }
        }
    }
    
    func startRecording(){
        guard let captureSession = captureSession, !captureSession.outputs.contains(videoFileOutput) else { return }
        captureSession.addOutput(videoFileOutput)
        
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let filePath = documentsURL.appendingPathComponent("recorded_video_\(Date().timeIntervalSince1970).mov")
        
        videoFileOutput.startRecording(to: filePath, recordingDelegate: recordingDelegate)
        // 启动倒计时
        secondsToReachGoal = 30
        recorded = 0
        startTimers()
    }
    
    func stopRecording(){
        guard videoFileOutput.isRecording else { return }
        videoFileOutput.stopRecording()
        // 停止倒计时
        shakeCountDown?.invalidate()
        shakeCountDown = nil
        if let captureSession = captureSession, captureSession.outputs.contains(videoFileOutput) {
            captureSession.removeOutput(videoFileOutput)
        }
        print("🔴 录制已停止")
    }
}

额外优化说明

  • 新增了音频输入采集,录制的视频默认带声音
  • 优化了录制文件命名,避免重复覆盖历史录制文件
  • 优化了预览图层填充模式,全屏展示不会出现黑边
  • 增加了状态判断,避免重复启停录制导致的崩溃

内容的提问来源于stack exchange,提问作者Krunal Nagvadia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 16:42:03