Extract thumbnail from video url

前端 未结 6 693
悲哀的现实
悲哀的现实 2021-01-05 15:57

I have to extract a thumbnail from a video (from url) and I use this code:

NSString *stringUrl = video.stringurl;
NSURL *url = [NSURL URLWithString:stringUrl         


        
6条回答
  •  一生所求
    2021-01-05 17:01

    If you are using MPMoviePlayerController then you can use this code to generate thumbnail from video URL.

    NSString *stringUrl = video.stringurl;
    NSURL *url = [NSURL URLWithString:stringUrl];
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
    UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
    

    But, using this code, player will start autoplaying audio. So, you have to stop the player with this code :

    //Player autoplays audio on init
    [player stop];
    

    Update :

    Error save image Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed"(OSStatus error -12792.)", NSLocalizedFailureReason=An unknown error occurred (-12792)}

    The Error is probably due to use of URLWithString. I think you should use -fileURLWithPath instead of URLWithString.

    Sample Code :

    NSString *stringUrl = video.stringurl;
    NSURL *vidURL = [NSURL fileURLWithPath:stringUrl];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidURL options:nil];
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    NSError *err = NULL;
    CMTime time = CMTimeMake(1, 60);
    
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
    UIImage *thumbnail = [UIImage imageWithCGImage:imgRef];
    

提交回复
热议问题