Thursday, February 18, 2016

Objective C getting first frame of a video

When we have a list of videos in our server, We need to display them in a table view along with the video starting frame. In this case we can download the video first and with the help of MPMoviePlayerController class thumbnailImageAtTime method we can grab the first or any frame of the video by giving the time interval option.




   
    MPMoviePlayerController *theMovie = [[MPMoviePlayerController allocinitWithContentURL:     
                                                                                           [NSURL fileURLWithPath:tempPath]];                                                     

    theMovie.controlStyle = MPMovieControlStyleNone;

    theMovie.shouldAutoplay=NO;

    UIImage *frame = [theMovie thumbnailImageAtTime:1 timeOption:MPMovieTimeOptionExact];              

    self.imageView.image =  frame;






                         



thumbnailImageAtTime is deprecated in iOS 7.0. We can use below method to get the first or any time frame of the video.




   - (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes 

                                                                                     timeOption:(MPMovieTimeOption)option;



Here are the MPMovieTimeOption options.

  •     MPMovieTimeOptionNearestKeyFrame,
  •     MPMovieTimeOptionExact


Unlike thumbnailImageAtTime, requestThumbnailImagesAtTimes takes array of time interval numbers. This doesn't return array of images for those specified time intervals. We need to observe for MPMoviePlayerThumbnailImageRequestDidFinishNotification 
notification when we call for requestThumbnailImagesAtTimes.




  [[NSNotificationCenter defaultCenter] addObserver:self    

              selector:@selector(MPMoviePlayerThumbnailImageRequestDidFinishNotification:)                  name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:moviePlayer];



We can access individual images in the selector method like shown below.




  -(void)MPMoviePlayerThumbnailImageRequestDidFinishNotification: (NSNotification*)note

   {

       NSDictionary * info = [note userInfo];

       UIImage *img = (UIImage *) [info objectForKey:MPMoviePlayerThumbnailImageKey];                                                           
       if(image!=NULL){

             [thumbView setImage:image];
       }

   }



Hope this post is useful. Feel free to comment in case of any queries.

No comments:

Post a Comment