2013-04-24 68 views
3

我尝试使用下面的代码ALAssets库中读取视频数据ALAssets获取视频数据

 ALAssetRepresentation *rep = [asset defaultRepresentation]; 
     Byte *buffer = (Byte*)malloc(rep.size); 
     NSError *error = nil; 
     NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:&error]; 
     NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES]; 

它工作正常的小视频以及图片,但如果想获得一个大的视频中,代码崩溃说

*终止应用程序由于未捕获的异常 'NSInvalidArgumentException',原因是:“* - [NSConcreteData initWithBytes:长度:副本:freeWhenDone:bytesAreVM:]:荒谬的长度:4294967295,最大尺寸:2147483648字节'

我不知道发生了什么事。任何一个想法?

在此先感谢!

+0

发生异常时,rep.size的值是多少? – RegularExpression 2013-04-24 18:16:38

+0

它的价值是522523356 – Advaith 2013-04-25 06:01:11

回答

1

我找到了解决方案。我猜这次崩溃可能是由于我们上传大文件时内存大量增加,因为我正在缓冲数据。现在我读取文件数据为5 MB块,并修复了崩溃。我在下面粘贴我的代码。

- (NSData *)getDataPartAtOffset:(NSInteger)offset { 
__block NSData *chunkData = nil; 
if (fileAsset_){ 
    static const NSUInteger BufferSize = PART_SIZE; // 5 MB chunk 
    ALAssetRepresentation *rep = [fileAsset_ defaultRepresentation]; 
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer)); 
    NSUInteger bytesRead = 0; 
    NSError *error = nil; 

    @try 
    { 
     bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:&error]; 
     chunkData = [NSData dataWithData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]]; 
    } 
    @catch (NSException *exception) 
    { 
     free(buffer); 
     chunkData = nil; 
     // Handle the exception here... 
    } 

    free(buffer); 
} else { 
    NSLog(@"failed to retrive Asset"); 
} 
return chunkData; 

}

我,我会调用该函数

int offset = 0; // offset that keep tracks of chunk data 

    do { 
     @autoreleasepool { 
      NSData *chunkData = [self getDataPartAtOffset:offset];; 

      if (!chunkData || ![chunkData length]) { // finished reading data 
       break; 
      } 

      // do your stuff here 

      offset +=[chunkData length]; 
     } 
    } while (1);