iOS偶尔会写入空视频文件

标签 ios swift

我有一个 Movie 类,它有一个 UIImage 数组,我将其写入 H264 文件。它可以工作,但偶尔会写入不包含任何内容的视频文件,但文件大小仍设置为非零大小。

这是我编写的代码。我是 iOS 开发的新手,所以这是从互联网上复制的,所以我可能不完全理解它在做什么。希望有人可以提出更好的方法。

frame 是循环中的一个UIImage实例

func writeAnimationToMovie() {
    var error: NSError?

    writer.startWriting()
    writer.startSessionAtSourceTime(kCMTimeZero)

    var buffer: CVPixelBufferRef

    var frameCount = 0
    for frame in self.photos {
        buffer = createPixelBufferFromCGImage(frame.CGImage)

        var appendOk = false
        var j = 0
        while (!appendOk && j < 30) {
            if pixelBufferAdaptor.assetWriterInput.readyForMoreMediaData {
                let frameTime = CMTimeMake(Int64(frameCount), Int32(fps))
                appendOk = pixelBufferAdaptor.appendPixelBuffer(buffer, withPresentationTime: frameTime)
                // appendOk will always be false
                NSThread.sleepForTimeInterval(0.05)
            } else {
                NSThread.sleepForTimeInterval(0.1)
            }
            j++
        }
        if (!appendOk) {
            println("Doh, frame \(frame) at offset \(frameCount) failed to append")
        }

        frameCount++
    }

    input.markAsFinished()

    writer.finishWritingWithCompletionHandler({
        if self.writer.status == AVAssetWriterStatus.Failed {
            println("oh noes, an error: \(self.writer.error.description)")
        } else {
            let content = NSFileManager.defaultManager().contentsAtPath(self.fileURL.path!)
            println("wrote video: \(self.fileURL.path) at size: \(content?.length)")
        }
    })
}

func createPixelBufferFromCGImage(image: CGImageRef) -> CVPixelBufferRef {
    let options = [
        "kCVPixelBufferCGImageCompatibilityKey": true,
        "kCVPixelBufferCGBitmapContextCompatibilityKey": true
    ]

    let frameSize = CGSizeMake(CGFloat(CGImageGetWidth(image)), CGFloat(CGImageGetHeight(image)))

    var pixelBufferPointer = UnsafeMutablePointer<Unmanaged<CVPixelBuffer>?>.alloc(1)

    var status:CVReturn = CVPixelBufferCreate(
        kCFAllocatorDefault,
        UInt(frameSize.width),
        UInt(frameSize.height),
        OSType(kCVPixelFormatType_32ARGB),
        options,
        pixelBufferPointer
    )

    var lockStatus:CVReturn = CVPixelBufferLockBaseAddress(pixelBufferPointer.memory?.takeUnretainedValue(), 0)

    var pxData:UnsafeMutablePointer<(Void)> = CVPixelBufferGetBaseAddress(pixelBufferPointer.memory?.takeUnretainedValue())
    let bitmapinfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.NoneSkipFirst.rawValue)
    let rgbColorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()

    var context:CGContextRef = CGBitmapContextCreate(
        pxData,
        UInt(frameSize.width),
        UInt(frameSize.height),
        8,
        4 * CGImageGetWidth(image),
        rgbColorSpace,
        bitmapinfo
    )

    CGContextDrawImage(context, CGRectMake(0, 0, frameSize.width, frameSize.height), image)

    CVPixelBufferUnlockBaseAddress(pixelBufferPointer.memory?.takeUnretainedValue(), 0)

    return pixelBufferPointer.memory!.takeUnretainedValue()
}

编辑 似乎没有任何内容的文件不会像其他可用的电影那样播放。如果我使用 exiftool 查看工作文件,这就是我得到的

$ exiftool 20242697651186-o.mp4

ExifTool Version Number         : 9.76
File Name                       : 20242697651186-o.mp4
Directory                       : .
File Size                       : 74 kB
File Modification Date/Time     : 2014:12:05 11:07:29-05:00
File Access Date/Time           : 2014:12:08 10:12:29-05:00
File Inode Change Date/Time     : 2014:12:05 11:07:29-05:00
File Permissions                : rw-r--r--
File Type                       : MP4
MIME Type                       : video/mp4
Major Brand                     : MP4 v2 [ISO 14496-14]
Minor Version                   : 0.0.1
Compatible Brands               : mp41, mp42, isom
Movie Data Size                 : 74741
Movie Data Offset               : 44
Movie Header Version            : 0
Create Date                     : 2014:12:05 16:07:32
Modify Date                     : 2014:12:05 16:07:32
Time Scale                      : 600
Duration                        : 0.50 s
Preferred Rate                  : 1
Preferred Volume                : 100.00%
Preview Time                    : 0 s
Preview Duration                : 0 s
Poster Time                     : 0 s
Selection Time                  : 0 s
Selection Duration              : 0 s
Current Time                    : 0 s
Next Track ID                   : 2
Track Header Version            : 0
Track Create Date               : 2014:12:05 16:07:32
Track Modify Date               : 2014:12:05 16:07:32
Track ID                        : 1
Track Duration                  : 0.50 s
Track Layer                     : 0
Track Volume                    : 0.00%
Matrix Structure                : 1 0 0 0 1 0 0 0 1
Image Width                     : 640
Image Height                    : 480
Media Header Version            : 0
Media Create Date               : 2014:12:05 16:07:32
Media Modify Date               : 2014:12:05 16:07:32
Media Time Scale                : 600
Media Duration                  : 0.50 s
Media Language Code             : und
Handler Type                    : Video Track
Handler Description             : Core Media Video
Graphics Mode                   : srcCopy
Op Color                        : 0 0 0
Compressor ID                   : avc1
Source Image Width              : 640
Source Image Height             : 480
X Resolution                    : 72
Y Resolution                    : 72
Bit Depth                       : 24
Video Frame Rate                : 8
Avg Bitrate                     : 1.2 Mbps
Image Size                      : 640x480
Rotation                        : 0

这是一个不起作用的文件。它没有所有的元数据

$ exiftool 20242891987099-o.mp4

ExifTool Version Number         : 9.76
File Name                       : 20242891987099-o.mp4
Directory                       : .
File Size                       : 75 kB
File Modification Date/Time     : 2014:12:05 11:07:37-05:00
File Access Date/Time           : 2014:12:08 10:12:36-05:00
File Inode Change Date/Time     : 2014:12:05 11:07:37-05:00
File Permissions                : rw-r--r--
File Type                       : MP4
MIME Type                       : video/mp4
Major Brand                     : MP4 v2 [ISO 14496-14]
Minor Version                   : 0.0.1
Compatible Brands               : mp41, mp42, isom
Movie Data Size                 : 76856
Movie Data Offset               : 44

最佳答案

你有几个问题。我不确定您所说的“不包含任何内容”到底是什么意思,但希望其中之一会有所帮助(如果没有,您无论如何都应该实现它们):

  1. 您通过调用 sleepForTimeInterval() 阻塞了线程,这可能会导致问题。 This answer建议移动运行循环而不是休眠,这是一个稍微好一点的解决方案,但是 the readyForMoreMediaData documentation有一个更好的建议:

    This property is observable using key-value observing (see Key-Value Observing Programming Guide). Observers should not assume that they will be notified of changes on a specific thread.

    无需运行循环并询问它是否可用,只需让对象告诉您何时可以使用 KVO 进行更多操作。

  2. 在您的 createPixelBufferFromCGImage 方法中,您在任何时候都不会检查失败。例如,您应该处理 pixelBufferPointer.memory?nil 的可能性。

基本上,我假设其中一件事情正在发生:

  • j 命中 30 并且由于线程被阻塞,因此尚未写入任何内容。在这种情况下,您将写入一个具有正确文件大小的空文件。
  • createPixelBufferFromCGImage 正在返回意外数据,您随后将这些数据写入磁盘

关于iOS偶尔会写入空视频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320868/

相关文章:

ios - ios 6 中带有文本字段和三个按钮问题的 UIAlertView

ios - 可以使用Core Audio SDK开发iOS音效单元吗?

ios - App Store Connect 如何添加阿拉伯语截图和文字?

Swift:api调用中的预期表达式错误

iOS 编程方式的宽高比约束在 UITableviewcell 中被打破

ios - 在初始化程序的实现中必须完成什么?

objective-c - 呈现 UIViewControllers 查看 Storyboard

iphone - 如何同时执行两个 IBAction?

iOS - 推送通知在辞职的 IPA 中不起作用

swift - 在 UICollectionView 中点击按钮时字段 UITextField