iOS:在处理每帧视频并用音频文件重写时收到内存警告

标签 ios swift

我需要导出视频,同时用背景图像操纵它的每一帧。现在我用最终帧再次组装它,并使用 AVAssetWriter 写入它,并收到 50 帧的内存警告。

我正在使用 swift-video-generator 并发送所有帧和单个音频文件以生成最终输出。

    private  func getVideoAllFramesAndAppendItWithFinalCanvasImageBackground(asset:AVAsset, backgroundImage:UIImage, videoRect:CGRect) {
        var frameCount:Int = 0
        let lastIndex:Int = 130 //Checking optimize way to handle all frame without reading it in memory
        let assetReader = try! AVAssetReader(asset: asset)
        let assetTrack = asset.tracks(withMediaType: AVMediaType.video).first!
        let assetReaderOutputSettings = [
            kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA)
        ]
        let assetReaderOutput = AVAssetReaderTrackOutput(track: assetTrack, outputSettings: assetReaderOutputSettings)
        assetReaderOutput.alwaysCopiesSampleData = false
        assetReader.add(assetReaderOutput)
        assetReader.startReading()

        var sample: CMSampleBuffer? = assetReaderOutput.copyNextSampleBuffer()
        while (sample != nil) {
            frameCount = frameCount + 1
            print(frameCount)
            sample = assetReaderOutput.copyNextSampleBuffer()
            if sample != nil {
                self.convertBufferImageToUIImage(sampleBuffer: sample!, canvasExportImage: backgroundImage, videoRect: videoRect)

            }
            if frameCount == lastIndex {
                break
            }
        }
        print(frameCount)
        if lastIndex == frameCount {
           self.writeVideoWithFinalFrames(finalFrames: self.finalVideoExportFrames, videoAsset:asset)
        }
    }

有没有什么方法可以做到这一点,而不会面临 iOS 中的内存问题?

最佳答案

你能尝试这样的事情吗?

while (assetReaderOutput.copyNextSampleBuffer() != nil) {
            autoreleasepool {
                frameCount = frameCount + 1
                print(frameCount)
                let sample: CMSampleBuffer? = assetReaderOutput.copyNextSampleBuffer()
                if sample != nil {
                    self.convertBufferImageToUIImage(sampleBuffer: sample!, canvasExportImage: backgroundImage, videoRect: videoRect)

                }
                if frameCount == lastIndex {
                    break
                }
            }
        }

希望对你有帮助

关于iOS:在处理每帧视频并用音频文件重写时收到内存警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57142449/

相关文章:

swift - 无法将 CGFloat 类型的值分配给 CGFloat 类型的值

ios - 添加 subview 后只出现白色矩形

ios - 在 HeaderInSection 中查看大小不增加

ios - 返回IOS Root View

ios - 有没有办法在用户每次打开应用程序时不重新下载图像?

swift - 无法在没有参数的情况下调用类型 "closure"的初始值设定项

swift - 创建一个循环,每次调用一个值时加 40

swift - 如何处理主队列上的多个 moc

iphone - Plist 到 UITableView

iphone - AFNetworking 卡住其他 Action