我正在尝试使用以下代码访问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:length:copy:freeWhenDone:bytesAreVM:]:absurd length:4294967295,最大大小:2147483648字节“
我不知道发生了什么。任何一个想法?
提前致谢!
答案 0 :(得分: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);
答案 1 :(得分:1)
chilitechno's位here为我工作。