swift 屏幕录制

步骤 1:导入 ReplayKit

swift 复制代码
import ReplayKit

步骤 2:开始录屏

swift 复制代码
let screenRecorder = RPScreenRecorder.shared()
// 麦克风或系统音频
screenRecorder.isMicrophoneEnabled = true

func startRecording() {
    guard screenRecorder.isAvailable else {
        print("Screen recording is not available on this device.")
        return
    }

    screenRecorder.startRecording { error in
        if let error = error {
            print("Error starting recording: \(error.localizedDescription)")
        } else {
            print("Recording started successfully.")
        }
    }
}

步骤 3:停止录屏

swift 复制代码
func stopRecording() {
    screenRecorder.stopRecording { previewController, error in
        if let error = error {
            print("Error stopping recording: \(error.localizedDescription)")
        } else {
            print("Recording stopped successfully.")
        }

        // 可选择展示预览界面
        if let previewController = previewController {
            previewController.previewControllerDelegate = self
            self.present(previewController, animated: true)
        }
    }
}
extension YourViewController: RPPreviewViewControllerDelegate {
    func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
        previewController.dismiss(animated: true, completion: nil)
    }
}

4. 不预览直接保存录制内容

swift 复制代码
RPScreenRecorder.shared().startCapture { sampleBuffer, bufferType, error in
    if let error = error {
        print("Error capturing: \(error.localizedDescription)")
        return
    }

    // 处理视频和音频数据
    if bufferType == .video {
        print("Captured video frame.")
    } else if bufferType == .audioApp || bufferType == .audioMic {
        print("Captured audio frame.")
    }
} completionHandler: { error in
    if let error = error {
        print("Error starting capture: \(error.localizedDescription)")
    } else {
        print("Capture started successfully.")
    }
}
相关推荐
HarderCoder17 小时前
Swift 6 并发时代,如何优雅地“抢救”你的单例?
swift
zhangmeng17 小时前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
HarderCoder17 小时前
SwiftUI 踩坑记:onAppear / task 不回调?90% 撞上了“空壳视图”!
swift
HarderCoder17 小时前
@isolated(any) 深度解析:Swift 并发中的“隔离追踪器”
swift
大熊猫侯佩21 小时前
桃花岛 Xcode 构建秘籍:Swift 中的 “Feature Flags” 心法
app·xcode·swift
用户091 天前
SwiftUI Charts 函数绘图完全指南
ios·swiftui·swift
YungFan1 天前
iOS26适配指南之UIColor
ios·swift
HarderCoder1 天前
Swift 6.2 新特性 `@concurrent` 完全导读
swift
HarderCoder1 天前
Swift 里的“橡皮擦”与“标签”——搞懂 existentials 与 primary associated type
swift
用户092 天前
TipKit与CloudKit同步完全指南
ios·swift