步骤 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.")
}
}