Миниатюра ALAsset в определенное время

Я работаю над приложением для iPhone для загрузки видеофайлов на определенную платформу, и мне бы очень хотелось, чтобы у меня была возможность представить, скажем, десять разных миниатюр для одного и того же видео, которые пользователь может выбрать.

Проблема в том, что ALAsset предоставляет только метод миниатюр, который просто возвращает миниатюру по умолчанию. Я прочитал документацию по ALAssetRepresentation и ALAsset и не могу найти способ получить миниатюру для конкретной метки времени.

Я полагаю, что одним из вариантов будет использование чего-то похожего на libav для получения миниатюр, но это выглядит немного "слишком" для чего-то подобного. Может ли кто-нибудь помочь мне в этом?

С наилучшими пожеланиями,
Ник

2 ответа

Я думаю, что это поможет вам, и вы также можете видеть в этом приглашении, что в ALAsset отсутствует временная метка эскиза видеофайла.

{

  if ([theAsset valueForProperty:ALAssetPropertyType] == ALAssetTypeVideo) {

        // Black semi-transparent background at the bottom of the item
        CGRect containerFrame = CGRectMake(0, frame.size.height - AGIPC_ITEM_HEIGHT, frame.size.width, AGIPC_ITEM_HEIGHT);
        UIView *containerForMovieInfo = [[[UIView alloc] initWithFrame:containerFrame] autorelease];
        containerForMovieInfo.backgroundColor = [UIColor blackColor];
        containerForMovieInfo.alpha = 0.7f;

        // Movie icon on left side
        CGRect movieFrame = CGRectMake(4, 60, 26, 15);
        UIImageView *movieImageView = [[[UIImageView alloc] initWithFrame:movieFrame] autorelease];
        if (IS_IPAD()) {
            movieImageView.image = [UIImage imageNamed:@"AGIPC-Movie-iPad"];
        } else {
            movieImageView.image = [UIImage imageNamed:@"AGIPC-Movie-iPhone"];
        }
        [containerForMovieInfo addSubview:movieImageView];

        // Movie duration on right side
        if ([theAsset valueForProperty:ALAssetPropertyDuration] != ALErrorInvalidProperty) {
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setDateFormat:@"mm:ss"];
            CGRect durationFrame = CGRectMake(frame.size.width - 26 - 4, 60, 26, 15);
            UILabel *durationView = [[[UILabel alloc] initWithFrame:durationFrame] autorelease];
            durationView.backgroundColor = [UIColor clearColor];
            durationView.textColor = [UIColor whiteColor];
            durationView.text = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:[[theAsset valueForProperty:ALAssetPropertyDuration] doubleValue]]];
            durationView.font = [UIFont systemFontOfSize:10];
            [containerForMovieInfo addSubview:durationView];
        }

        [self addSubview:containerForMovieInfo];
    }

}

И последнее, но не менее важное: вы должны создать изображение камеры самостоятельно.

// Get URL from ALAsset* asset:
NSURL* assetURL = [asset valueForProperty:ALAssetPropertyAssetURL];

// Create AVURLAsset using this URL (assetOptions is optional):
NSDictionary* assetOptions = nil;
// assetOptions = @{AVURLAssetPreferPreciseDurationAndTimingKey : @(YES)};
AVAsset* avAsset = [[AVURLAsset alloc] initWithURL:assetURL options:assetOptions];

// Create generator:
AVAssetImageGenerator* generator = [[AVAssetImageGenerator alloc] initWithAsset:avAsset];
generator.appliesPreferredTrackTransform = YES;

// Create array with CMTimes of thumbnails using your own logic.
// (Use +(NSValue*)valueWithCMTime:(CMTime)time to add CMTime in array).
NSArray* times = [self generateThumbnailTimesForVideo:avAsset];

// Generate thumbnail images asynchronously:
[generator generateCGImagesAsynchronouslyForTimes:times
                                completionHandler:^(CMTime requestedTime,
                                                    CGImageRef image,
                                                    CMTime actualTime,
                                                    AVAssetImageGeneratorResult result,
                                                    NSError* error)
    {
        // This block is performed for each CMTime in times array.
        UIImage* thumbnail = [[UIImage alloc] initWithCGImage:image];
    }
];

Синхронный способ получить миниатюру в любое время

// PS: SYNC method:
CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&error];
UIImage* thumbnail = [[UIImage alloc] initWithCGImage:image];
Другие вопросы по тегам