将Samplebuffer保存到相机滚动快速

时间:2018-02-02 23:14:41

标签: ios swift replaykit

我使用ReplayKit录制视频:

      let sharedRecorder = RPScreenRecorder.shared()
    sharedRecorder.startCapture(handler: { (sampleBuffer, sampleType, error) in
        print("VIDEO INPUT:", sampleBuffer)

    }, completionHandler: { (error) in

    })

现在如何将视频(样本缓冲区)保存到相机胶卷?我正在寻找明确的例子!谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用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()
                }
        }

SaveToCameraRoll():

        PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: "YOUR VIDEO FILE URL")
    }) { saved, error in
        if saved {
            print("Save")
        } else {
            print("error to save - \(error)")
        }
    }