我正在使用this SO answer的代码段
但是总是得到pixelBufferAdaptor.pixelBufferPool == nil
,我该如何解决?
```
func writeImagesAsMovie(allImages: [UIImage], videoPath: String, videoSize: CGSize, videoFPS: Int32) {
// Create AVAssetWriter to write video
guard let assetWriter = createAssetWriter(path: videoPath, size: videoSize) else {
print("Error converting images to video: AVAssetWriter not created")
return
}
// If here, AVAssetWriter exists so create AVAssetWriterInputPixelBufferAdaptor
let writerInput = assetWriter.inputs.filter { $0.mediaType == AVMediaType.video }.first!
let sourceBufferAttributes: [String: AnyObject] = [
kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32ARGB) as AnyObject,
kCVPixelBufferWidthKey as String: videoSize.width as AnyObject,
kCVPixelBufferHeightKey as String: videoSize.height as AnyObject
]
let pixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: writerInput, sourcePixelBufferAttributes: sourceBufferAttributes)
if assetWriter.canAdd(writerInput) {
assetWriter.add(writerInput)
} else {
print("Cannot add asset writer")
}
// Start writing session
assetWriter.startWriting()
assetWriter.startSession(atSourceTime: kCMTimeZero)
if pixelBufferAdaptor.pixelBufferPool == nil {
print("Error converting images to video: pixelBufferPool nil after starting session")
return
}
}
func createAssetWriter(path: String, size: CGSize) -> AVAssetWriter? {
// Convert <path> to NSURL object
let pathURL = URL.init(fileURLWithPath: path)
// Return new asset writer or nil
do {
// Create asset writer
guard let newWriter = try? AVAssetWriter(outputURL: pathURL, fileType: AVFileType.mp4) else {
fatalError("AVAssetWriter error")
}
// Define settings for video input
let videoSettings: [String: AnyObject] = [
AVVideoCodecKey: AVVideoCodecType.h264 as AnyObject,
AVVideoWidthKey: size.width as AnyObject,
AVVideoHeightKey: size.height as AnyObject
]
// Add video input to writer
let assetWriterVideoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)
newWriter.add(assetWriterVideoInput)
// Return writer
print("Created asset writer for \(size.width)x\(size.height) video")
return newWriter
} catch {
print("Error creating asset writer: \(error)")
return nil
}
}
stream.writeImagesAsMovie(allImages: stream.imageArray, videoPath: "video.mp4",
videoSize: stream.imageArray[0].size, videoFPS: 10)
```