MPMoviePlayerControlle thumbnailImageAtTime:timeOption:给出空的UIImage

时间:2011-08-24 16:02:31

标签: ios mpmovieplayercontroller

我用它来获取视频的预览缩略图:

- (void)createThumb {
NSInteger paddingLeft = 22;
NSInteger paddingTop = 22;

CGFloat frameWidth = self.preview.frame.size.width - (2 * paddingLeft); 
CGFloat frameHeight = self.preview.frame.size.height - (2 * paddingTop);

CGSize size = CGSizeMake(frameWidth, frameHeight);


MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] 
                               initWithContentURL:self.fileUrl];

NSLog(@"File url %@",self.fileUrl);

UIImage *thumbnail = [mp thumbnailImageAtTime:0.0 
                                   timeOption:MPMovieTimeOptionNearestKeyFrame];
[mp stop];
[mp release];
if (!thumbnail){
    thumbnail = [UIImage imageNamed:@"video_dummy"];
}
  thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];
}

但它不起作用。由此产生的UIImage总是为零。有人可以帮忙吗?

谢谢, 菲利普

1 个答案:

答案 0 :(得分:4)

好的,我找到了解决方案:

我使用它来代替使用MPMoviePlayerController,它可以更好地完成工作:

 NSInteger paddingLeft = 24;
NSInteger paddingTop = 24;

CGFloat frameWidth = self.preview.frame.size.width - (2 * paddingLeft); 
CGFloat frameHeight = self.preview.frame.size.height - (2 * paddingTop);

CGSize size = CGSizeMake(frameWidth, frameHeight);

AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.fileUrl options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);

AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
    if (result == AVAssetImageGeneratorSucceeded) {
        UIImage *thumbnail=[[UIImage imageWithCGImage:im] retain];
        thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];

        NSData *thumbData = UIImageJPEGRepresentation(thumb, 0.2);

        [thumbData writeToFile:  [[[NSFileManager defaultManager] contentDirectory] stringByAppendingPathComponent:self.thumbFilename] atomically: NO];
        [generator release];
        [self.preview setImage: thumb];   
    }
    else {
        UIImage *thumbnail=[[UIImage imageNamed:@"video_dummy"] retain];
        thumb = [[thumbnail gtm_imageByResizingToSize:size preserveAspectRatio:YES trimToFit:NO] retain];

        NSData *thumbData = UIImageJPEGRepresentation(thumb, 0.2);

        [thumbData writeToFile:  [[[NSFileManager defaultManager] contentDirectory] stringByAppendingPathComponent:self.thumbFilename] atomically: NO];
        [generator release];
        [self.preview setImage: thumb];
    }
};

CGSize maxSize = CGSizeMake(320, 180);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];    

所以如果你想这样做,请使用AVFramework方法