2010-09-20 110 views
14

我想將CGImage轉換爲CMSampleBufferRef,並使用appendSampleBuffer:方法將它附加到AVAssetWriterInput。我設法使用以下代碼獲得CMSampleBufferRef,但appendSampleBuffer:只是在我提供CMSampleBufferRef時返回NO。我究竟做錯了什麼?如何將CGImage轉換爲CMSampleBufferRef?

- (void) appendCGImage: (CGImageRef) frame 
{ 
    const int width = CGImageGetWidth(frame); 
    const int height = CGImageGetHeight(frame); 

    // Create a dummy pixel buffer to try the encoding 
    // on something simple. 
    CVPixelBufferRef pixelBuffer = NULL; 
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, 
     kCVPixelFormatType_32BGRA, NULL, &pixelBuffer); 
    NSParameterAssert(status == kCVReturnSuccess && pixelBuffer != NULL); 

    // Sample timing info. 
    CMTime frameTime = CMTimeMake(1, 30); 
    CMTime currentTime = CMTimeAdd(lastSampleTime, frameTime); 
    CMSampleTimingInfo timing = {frameTime, currentTime, kCMTimeInvalid}; 

    OSStatus result = 0; 

    // Sample format. 
    CMVideoFormatDescriptionRef videoInfo = NULL; 
    result = CMVideoFormatDescriptionCreateForImageBuffer(NULL, 
     pixelBuffer, &videoInfo); 
    NSParameterAssert(result == 0 && videoInfo != NULL); 

    // Create sample buffer. 
    CMSampleBufferRef sampleBuffer = NULL; 
    result = CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault, 
     pixelBuffer, true, NULL, NULL, videoInfo, &timing, &sampleBuffer); 
    NSParameterAssert(result == 0 && sampleBuffer != NULL); 

    // Ship out the frame. 
    NSParameterAssert(CMSampleBufferDataIsReady(sampleBuffer)); 
    NSParameterAssert([writerInput isReadyForMoreMediaData]); 
    BOOL success = [writerInput appendSampleBuffer:frame]; 
    NSParameterAssert(success); // no go :(
} 

P.S.我知道這段代碼中有內存泄漏,爲簡單起見我省略了一些代碼。

回答

7

啊哈,我完全錯過了AVAssetWriterInputPixelBufferAdaptor類,這是專門爲管道像素緩衝區寫入輸入。現在的代碼工作,即使沒有雜亂的CMSampleBuffer的東西。

+3

嗨,你可以請poste代碼,使其工作? – Ondrej 2012-05-06 19:51:12

+2

任何人都想出解決方案:-) – DogCoffee 2014-01-25 10:22:45

+0

嗨!你可以請與我們分享代碼嗎? – 2014-07-23 05:29:07

相關問題