При попытке записать и сохранить аудио / видео с помощью ReplayKit я получаю ошибки. Я использую
Xcode: Version 11.2.1
Swift 5
iOS 13
iPhone 7+ physical device
Когда я устанавливаю filePath, я уже использую URL (fileURLWithPath:) . Расширение файла и AVFileType
оба .mp4
. Я проверяю, существует ли файл в FileManager
, и если да, то удаляю его: do { try FileManager.default.removeItem(at: videoURL) }
. Я попытался изменить сам путь на «Library / Caches /», как в @ florianSAP answer , который не сработал.
Здесь 3 ошибки:
// 1. from recording
if !self.assetWriter.startWriting() {
print("Can't write")
return
}
// 2. from recording
if self.assetWriter.status == AVAssetWriter.Status.failed {
print("StartCapture Error Occurred, Status = \(self.assetWriter.status.rawValue), \(self.assetWriter.error?.localizedDescription) \(self.assetWriter.error?.debugDescription)")
return
}
// 3. this one is when trying to save the url in the PHAssetChangeRequest.creationRequestForAssetFromVideo completionHandler
if let error = error {
print("PHAssetChangeRequest Video Error: \(error.localizedDescription)")
return
}
// 4. this isn't an error but inside the switch rpSampleBufferType { } statement "not a video sample" kept printing out
Сообщения об ошибках:
Произошла ошибка StartCapture, Status = 3, Операция не может быть завершена Необязательно ( Домен ошибки = AVFoundationErrorDomain Code = -11800 «Операция не может быть завершена» UserInfo = {NSLocalizedFailureReason = Произошла неизвестная ошибка (-17508), NSLocalizedDescription = Операция не может быть завершена, NSUnderlyingError = 0x2833a93b0 {Ошибка домена = NSOSStatusEror 17508 "(null)"}})
PHAssetChangeRequest Ошибка видео: операция не может быть завершена. (Ошибка PHPhotosErrorDomain -1.)
Куда я не так?
Начать запись
let recorder = RPScreenRecorder.shared()
var assetWriter: AVAssetWriter!
var videoURL: URL!
var videoInput: AVAssetWriterInput!
var audioMicInput: AVAssetWriterInput!
guard let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else { return }
videoURL = URL(fileURLWithPath: documentsPath.appending(UUID().uuidString + ".mp4"))
guard let videoURL = videoURL else { return }
do {
try FileManager.default.removeItem(at: videoURL)
} catch {}
do {
try assetWriter = AVAssetWriter(outputURL: videoURL, fileType: .mp4) // AVAssetWriter(url: videoURL, fileType: .mp4) didn't make a difference
} catch {}
let videoSettings: [String : Any] = [
AVVideoCodecKey: AVVideoCodecType.h264,
AVVideoWidthKey: view.bounds.width,
AVVideoHeightKey: view.bounds.height
]
videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
videoInput.expectsMediaDataInRealTime = true
if assetWriter.canAdd(videoInput) {
assetWriter.add(videoInput)
}
let audioSettings: [String:Any] = [AVFormatIDKey : kAudioFormatMPEG4AAC,
AVNumberOfChannelsKey : 2,
AVSampleRateKey : 44100.0,
AVEncoderBitRateKey: 192000
]
audioMicInput = AVAssetWriterInput(mediaType: .audio, outputSettings: audioSettings)
audioMicInput.expectsMediaDataInRealTime = true
if assetWriter.canAdd(audioMicInput) {
assetWriter.add(audioMicInput)
}
guard recorder.isAvailable else { return }
recorder.startCapture(handler: { (cmSampleBuffer, rpSampleBufferType, err) in
if let err = err { return }
// I tried to check if this was ready and added the below code to it but it made no difference
// if CMSampleBufferDataIsReady(cmSampleBuffer) { ... the code below was put in here ... }
DispatchQueue.main.async {
switch rpSampleBufferType {
case .video:
if self.assetWriter.status == AVAssetWriter.Status.unknown {
if !self.assetWriter.startWriting() {
print("Can't write")
return
}
print("Starting writing")
self.assetWriter.startWriting()
self.assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(cmSampleBuffer))
}
if self.assetWriter.status == AVAssetWriter.Status.failed {
print("StartCapture Error Occurred, Status = \(self.assetWriter.status.rawValue), \(self.assetWriter.error?.localizedDescription) \(self.assetWriter.error?.debugDescription)")
return
}
if self.assetWriter.status == AVAssetWriter.Status.writing {
if self.videoInput.isReadyForMoreMediaData {
if self.videoInput.append(cmSampleBuffer) == false {
print("problem writing video")
}
}
}
case .audioMic:
if self.audioMicInput.isReadyForMoreMediaData {
print("audioMic data added")
self.audioMicInput.append(cmSampleBuffer)
}
default:
print("not a video sample")
}
}
}
}, completionHandler: { (error) in
if let error = error { return }
})
Остановить запись:
recorder.stopCapture { (error) in
if let error = error { return }
guard let videoInput = self.videoInput else { return }
guard let audioMicInput = self.audioMicInput else { return }
guard let assetWriter = self.assetWriter else { return }
guard let videoURL = videoURL else { return }
videoInput.markAsFinished()
audioMicInput.markAsFinished()
assetWriter.finishWriting(completionHandler: {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoUrl)
}) { (saved, error) in
if let error = error {
print("PHAssetChangeRequest Video Error: \(error.localizedDescription)")
return
}
if saved {
// ... show success message
}
}
})
}
RPScreenRecorder Делегат, который никогда не вызывается:
func screenRecorder(_ screenRecorder: RPScreenRecorder, didStopRecordingWith previewViewController: RPPreviewViewController?, error: Error?) {
if let error = error {
print(error.localizedDescription)
}
}