您可以使用 AVAssetWriter。
配置视频和输出设置:
var assetWriter:AVAssetWriter!
var videoInput:AVAssetWriterInput!
var audioInput:AVAssetWriterInput!
assetWriter = try! AVAssetWriter(outputURL: fileURL,
fileType: .mp4)
let videoOutputSettings: Dictionary<String, Any> = [
AVVideoCodecKey : AVVideoCodecType.h264,
AVVideoWidthKey : UIScreen.main.bounds.size.width,
AVVideoHeightKey : UIScreen.main.bounds.size.height
]
var channelLayout = AudioChannelLayout.init()
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D
let audioOutputSettings: [String : Any] = [
AVNumberOfChannelsKey: 1,
AVFormatIDKey: kAudioFormatMPEG4AAC,
AVSampleRateKey: 44100
]
videoInput = AVAssetWriterInput(mediaType: AVMediaType.video,outputSettings: videoOutputSettings)
audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio,outputSettings: audioOutputSettings)
videoInput.expectsMediaDataInRealTime = true
audioInput.expectsMediaDataInRealTime = true
assetWriter.add(videoInput)
assetWriter.add(audioInput)
在 startCapture 处理程序中:
RPScreenRecorder.shared().startCapture(handler: { (sample, bufferType, error) in
recordingHandler(error)
if CMSampleBufferDataIsReady(sample) {
DispatchQueue.main.async { [weak self] in
if self?.assetWriter.status == AVAssetWriter.Status.unknown {
print("AVAssetWriterStatus.unknown")
if !(self?.assetWriter.startWriting())! {
return
}
self?.assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
self?.startSesstion = true
}
}
if self.assetWriter.status == AVAssetWriter.Status.failed {
print("Error occured, status = \(String(describing: self.assetWriter.status.rawValue)), \(String(describing: self.assetWriter.error!.localizedDescription)) \(String(describing: self.assetWriter.error))")
recordingHandler(self.assetWriter.error)
return
}
if (bufferType == .video) {
if(self.videoInput.isReadyForMoreMediaData) && self.startSesstion {
print("Video Buffer Came")
self.videoInput.append(sample)
}
}
if (bufferType == .audioApp) {
if self.audioInput.isReadyForMoreMediaData {
print("Audio Buffer Came")
self.audioInput.append(sample)
}
}
if (bufferType == .audioMic) {
if self.audioInput.isReadyForMoreMediaData {
print("Mic Buffer Came")
self.audioInput.append(sample)
}
}
}
})
在 stopCapture 处理程序中:
RPScreenRecorder.shared().stopCapture{ (error) in
self.videoInput.markAsFinished()
self.audioInput.markAsFinished()
self.assetWriter.finishWriting {
SaveToCameraRoll()
}
}
保存到相机胶卷():
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: "YOUR VIDEO FILE URL")
}) { saved, error in
if saved {
print("Save")
} else {
print("error to save - \(error)")
}
}