14

我无法从我从 ALAsset 获得的 url 中检索 NSData

下面是我尝试过的代码:- 我总是将 NSData 设为 nil。

 NSData *webData = [NSData dataWithContentsOfURL:[asset defaultRepresentation].url];

我也尝试过这样的事情

 NSData *webData1 = [NSData dataWithContentsOfURL:[[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]]];

我从 ALAsset 获得的网址:-

资产库://asset/asset.MOV?id=1000000116&ext=MOV

我已经尝试了以下链接,该链接有效,但我需要不必要地写入临时位置,这非常耗时。

从 ALAsset 获取视频

任何正确方向的提示将不胜感激。

等待您的回复

4

2 回答 2

61

试试这个代码: -

ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc((NSUInteger)rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
于 2012-01-10T10:20:58.603 回答
17

字节缓冲区 = (Byte )malloc(rep.size); 如果 rep.size 太大,可能是 300M,那将是崩溃。所以试试这个代码:

+ (BOOL)writeDataToPath:(NSString*)filePath andAsset:(ALAsset*)asset
{
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    if (!handle) {
        return NO;
    }
    static const NSUInteger BufferSize = 1024*1024;

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;

    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:nil];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch (NSException *exception) {
            free(buffer);

            return NO;
        }
    } while (bytesRead > 0);

    free(buffer);
    return YES;
}
于 2013-07-17T08:09:18.507 回答