This has been asked before, but something must have changed in Swift since it was asked. I am trying to store CMSampleBuffer
objects returned from an AVCaptureSession
to be processed later. After some experimentation I discovered that AVCaptureSession
must be reusing its CMSampleBuffer
references. When I try to keep more than 15 the session hangs. So I thought I would make copies of the sample buffers. But I can't seem to get it to work. Here is what I have written:
var allocator: Unmanaged<CFAllocator>! = CFAllocatorGetDefault()
var bufferCopy: UnsafeMutablePointer<CMSampleBuffer?>
let err = CMSampleBufferCreateCopy(allocator.takeRetainedValue(), sampleBuffer, bufferCopy)
if err == noErr {
bufferArray.append(bufferCopy.memory!)
} else {
NSLog("Failed to copy buffer. Error: \(err)")
}
This won't compile because it says that Variable 'bufferCopy' used before being initialized
. I've looked at many examples and they'll either compile and not work or they won't compile.
Anyone see what I'm doing wrong here?
Literally you're attempting to use the variable bufferCopy before it is initialized.
You've declared a type for it, but haven't allocated the memory it's pointing to.
You should instead create CMSampleBuffers using the following call https://developer.apple.com/library/tvos/documentation/CoreMedia/Reference/CMSampleBuffer/index.html#//apple_ref/c/func/CMSampleBufferCreate
You should be able to copy the buffer into this then (as long as the format of the buffer matches the one you're copying from).
You can simply pass a CMSampleBuffer?
variable (which, as an optional,
is implicitly initialized with nil
) as inout argument with
&
:
var bufferCopy : CMSampleBuffer?
let err = CMSampleBufferCreateCopy(kCFAllocatorDefault, buffer, &bufferCopy)
if err == noErr {
// ...
}
来源:https://stackoverflow.com/questions/35467847/create-a-copy-of-cmsamplebuffer-in-swift-2-0