如何从ALASSET ios获取视频大小

时间:2014-01-13 09:06:46

标签: ios objective-c alassetslibrary

在选择视频时,我尝试使用以下代码来获取视频大小,但我的应用已崩溃。我希望从ALAsset获取每个视频的大小,然后将它们添加到Array。怎么办?请给我一些建议。感谢。

    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = (UICollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
    UIImageView *OverlayImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 75, 75)];
    OverlayImageView.image = [UIImage imageNamed:@"Overlay-old.png"];
    [cell addSubview:OverlayImageView];
     alasset = [allVideos objectAtIndex:indexPath.row];
     NSDate* date = [alasset valueForProperty:ALAssetPropertyDate];
    NSLog(@"Date Time Modify %@",date);


    //get size of video
    ALAssetRepresentation *rep = [alasset 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];
    NSLog(@"Size of video %@",data);
}

2 个答案:

答案 0 :(得分:3)

以下是在ALAssetRepresentation帮助下获取媒体长度的完整代码

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *cellIdentifier = @"CollectionCell";
        CollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        ALAsset *asset = self.arrAssetsMedia[indexPath.row];

        //To Show ThumbNailImage
        CGImageRef thumbnailImageRef = [asset thumbnail];
        UIImage *thumbnail = [UIImage imageWithCGImage:thumbnailImageRef];
        cell.cellMediaImage.image = thumbnail;

        //To get the FileSize
        ALAssetRepresentation *rep = [asset defaultRepresentation];
        int Filesize=(int)[rep size];
        [cell.lblMediaSize setText:[self stringFromFileSize:Filesize]];
        return cell;
    }

注意:大小采用字节的形式。将其转换为相关的表格,如MB,GB等。

调用方法

- (NSString *)stringFromFileSize:(int)theSize
{
    float floatSize = theSize;
    if (theSize<1023)
        return([NSString stringWithFormat:@"%i bytes",theSize]);
    floatSize = floatSize / 1024;
    if (floatSize<1023)
        return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
    floatSize = floatSize / 1024;
    if (floatSize<1023)
        return([NSString stringWithFormat:@"%1.1f MB",floatSize]);
    floatSize = floatSize / 1024;

    // Add as many as you like

    return([NSString stringWithFormat:@"%1.1f GB",floatSize]);
}

答案 1 :(得分:2)

使用NSLog(@"Size of video %d",data.length); //length returns the number of bytes contained in the receiver.

或使用ALAssetRepresentation size 返回表示文件的字节大小。