菜鸟教程小白 发表于 2022-12-11 19:10:32

ios - ReplayKit 保存视频失败首先尝试使用麦克风


                                            <p><p>场景 1:</p>

<ol>
<li>使用音频/视频写入器输入启动 AVAssetWriter。</li>
<li>使用 RPScreenRecorder 在没有麦克风的情况下开始录制并处理样本缓冲区。</li>
<li>文件在第一次尝试时可以很好地写入照片。</li>
</ol>

<p>场景 2:</p>

<ol>
<li>使用音频/视频写入器输入启动 AVAssetWriter。</li>
<li>使用 RPScreenRecorder 在启用<strong>麦克风</strong>的情况下开始录制并处理样本缓冲区。</li>
<li><p>第一次尝试写入文件失败。</p>

<p>UserInfo={NSLocalizedRecoverySuggestion=重试保存。, NSLocalizedDescription=无法保存, NSUnderlyingError=0x1c464f3c0 {Error Domain=NSOSStatusErrorDomain Code=-12412 "(null)"}}
2017-10-26 23:25:16.896673-0400 状态失败!:3 错误域=AVFoundationErrorDomain 代码=-11823“无法保存”</p></li>
</ol>

<p>第二次尝试效果很好。</p>

<p>我做错了什么?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><pre><code>import Foundation
import ReplayKit
import AVKit
import Photos

class ScreenRecorder
{
    var assetWriter:AVAssetWriter!
    var videoInput:AVAssetWriterInput!
    var audioInput:AVAssetWriterInput!

    var startSesstion = false

//let viewOverlay = WindowUtil()

    //MARK: Screen Recording
    func startRecording(withFileName fileName: String, recordingHandler:@escaping (Error?)-&gt; Void)
    {
      if #available(iOS 11.0, *)
      {
            let fileURL = URL(fileURLWithPath: ReplayFileUtil.filePath(fileName))
            assetWriter = try! AVAssetWriter(outputURL: fileURL, fileType:
                AVFileType.mp4)
            let videoOutputSettings: Dictionary&lt;String, Any&gt; = [
                AVVideoCodecKey : AVVideoCodecType.h264,
                AVVideoWidthKey : UIScreen.main.bounds.size.width,
                AVVideoHeightKey : UIScreen.main.bounds.size.height,
//                AVVideoCompressionPropertiesKey : [
//                  AVVideoAverageBitRateKey :425000, //96000
//                  AVVideoMaxKeyFrameIntervalKey : 1
//                ]
            ];
            var channelLayout = AudioChannelLayout.init()
            channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_D
            let audioOutputSettings: = [
                AVNumberOfChannelsKey: 6,
                AVFormatIDKey: kAudioFormatMPEG4AAC_HE,
                AVSampleRateKey: 44100,
                AVChannelLayoutKey: NSData(bytes: &amp;channelLayout, length: MemoryLayout.size(ofValue: channelLayout)),
                ]


            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)

            RPScreenRecorder.shared().startCapture(handler: { (sample, bufferType, error) in
                recordingHandler(error)

                if CMSampleBufferDataIsReady(sample)
                {

                  DispatchQueue.main.async { in
                        if self?.assetWriter.status == AVAssetWriterStatus.unknown {
                            print(&#34;AVAssetWriterStatus.unknown&#34;)
                            if !(self?.assetWriter.startWriting())! {
                              return
                            }
                            self?.assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
                            self?.startSesstion = true
                        }

//                  if self.assetWriter.status == AVAssetWriterStatus.unknown
//                  {
//                        self.assetWriter.startWriting()
//                        self.assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
//                        self?.startSesstion = true
                  }
                  if self.assetWriter.status == AVAssetWriterStatus.failed {

                        print(&#34;Error occured, status = \(String(describing: self.assetWriter.status.rawValue)), \(String(describing: self.assetWriter.error!.localizedDescription)) \(String(describing: self.assetWriter.error))&#34;)
                         recordingHandler(self.assetWriter.error)
                        return
                  }
                  if (bufferType == .video)
                  {
                        if(self.videoInput.isReadyForMoreMediaData) &amp;&amp; self.startSesstion {
                            self.videoInput.append(sample)
                        }
                  }
                  if (bufferType == .audioApp)
                  {
                        if self.audioInput.isReadyForMoreMediaData
                        {
                            //print(&#34;Audio Buffer Came&#34;)
                            self.audioInput.append(sample)
                        }
                  }
                }
            }) { (error) in
                recordingHandler(error)
//                debugPrint(error)
            }
      } else
      {
            // Fallback on earlier versions
      }
    }
    func stopRecording(isBack: Bool, aPathName: String ,handler: @escaping (Error?) -&gt; Void)
    {

      //var isSucessFullsave = false
      if #available(iOS 11.0, *)
      {
            self.startSesstion = false
            RPScreenRecorder.shared().stopCapture{ (error) in
                self.videoInput.markAsFinished()
                self.audioInput.markAsFinished()

                handler(error)
                if error == nil{
                  self.assetWriter.finishWriting{
                         self.startSesstion = false
                        print(ReplayFileUtil.fetchAllReplays())
                        if !isBack{
                            self.PhotosSaveWithAurtorise(aPathName: aPathName)
                        }else{
                            self.deleteDirectory()
                        }
                  }
                }else{
                     self.deleteDirectory()
                }
            }
      }else {
         // print(&#34;Fallback on earlier versions&#34;)
      }
    }
    func PhotosSaveWithAurtorise(aPathName: String){
      if PHPhotoLibrary.authorizationStatus() == .authorized {
            self.SaveToCamera(aPathName: aPathName)
      } else {
            PHPhotoLibrary.requestAuthorization({ (status) in
                if status == .authorized {
                  self.SaveToCamera(aPathName: aPathName)
                }
            })
      }
    }
    func SaveToCamera(aPathName: String){
      PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: (ReplayFileUtil.fetchAllReplays().last)!)
      }) { saved, error in
            if saved {
               addScreenCaptureVideo(aPath: aPathName)
                print(&#34;Save&#34;)
            }else{
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: &#34;isScreenRecordFaildToSave&#34;), object: nil)
                print(&#34;error to save - \(error)&#34;)
            }
      }
    }
    func deleteDirectory(){
      ReplayFileUtil.delete()
    }

}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - ReplayKit 保存视频失败首先尝试使用麦克风,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/47063926/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/47063926/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - ReplayKit 保存视频失败首先尝试使用麦克风