How to get MPMoviePlayerViewController current Playing time?

1k Views Asked by At

I want to get current video playing time, not total duration.

My code is

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(MPMoviePlayerLoadStateDidChange:)
                                                 name:MPMoviePlayerLoadStateDidChangeNotification
                                               object:nil];

- (void)MPMoviePlayerLoadStateDidChange:(NSNotification *)notification {
    if ((self.moviePlayer.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK) {
        NSLog(@"content play length is %g seconds", self.moviePlayer.duration);
//        self.lblVideoDuration.text = [NSString stringWithFormat:@"%@", self.moviePlayer.duration];
    }
}

but above will give me total duration, but i don't want total duration.

if my Video duration is 1 minute and currently it play around 30 seconds, i want that live playback timing.

how can i get that?

I am able get Video Playback timing by start timer like this.

- (void)MPMoviePlayerLoadStateDidChange:(NSNotification *)notification {
    if (self.moviePlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [self.activityIndicator stopAnimating];
        [self.activityIndicator removeFromSuperview];
        [self startDurationTimer];
    }
}

- (void)startDurationTimer {
    self.durationTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(monitorMoviePlayback) userInfo:nil repeats:YES];
}

- (void)stopDurationTimer {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.durationTimer invalidate];
        self.durationTimer = nil;
    });
}

- (void)monitorMoviePlayback {
    double currentTime = floor(self.moviePlayer.currentPlaybackTime);
    double totalTime = floor(self.moviePlayer.duration);
    double minutesElapsed = floor(currentTime / 60.0);
    double secondsElapsed = fmod(currentTime, 60.0);

    NSLog(@"Minute = %f && Second = %f", minutesElapsed, secondsElapsed);
    }
}

but when i call stoptimer method , Timer is not invalidating or not stopped.

how can i invalidate Timer?

2

There are 2 best solutions below

4
Eugene Dudnyk On

If it is an option for you to use AVPlayerViewController instead of MPMoviePlayerViewController, you can get current time from it via

myAVPlayerViewController.player.currentTime;

Although it is recommended to switch to AVPlayerViewController, as MPMoviePlayerViewController is deprecated, to get current time from MPMoviePlayerViewController, you can use following code:

self.moviePlayer.currentPlaybackTime;
3
user3182143 On

Very perfect solution :-)

I created sample project and I worked out for your question.I got the solution.

As MPMoviePlayerController is deprecated we need to use AVPlayerViewController.

Apple Document says

The MPMoviePlayerController class is formally deprecated in iOS 9. (The MPMoviePlayerViewController class is also formally deprecated.) To play video content in iOS 9 and later, instead use the AVPictureInPictureController or AVPlayerViewController class from the AVKit framework, or the WKWebView class from WebKit.

So we must go with AVPlayerViewController or above one.Here I go with AVPlayerViewController.

I got the video play current time and duration.

First you need to add and import the AVKit and AVFoundation

ViewController.h

#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>


@interface ViewController : UIViewController

@property (strong, nonatomic) AVPlayerViewController *playerViewController;

- (IBAction)actionPlayVideoWithTime:(id)sender;


@end

ViewController.m

#import "ViewController.h"

@interface ViewController (){
    NSURL *vedioURL;
    AVPlayerItem *playerItem;
    AVPlayer *playVideo;
}

@end

@implementation ViewController

@synthesize playerViewController;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)actionPlayVideoWithTime:(id)sender {
    NSString *strVideoURL   =   [[NSBundle mainBundle] pathForResource:@"IMG_0034" ofType:@"MOV"];
    vedioURL =[NSURL fileURLWithPath:strVideoURL];
    playerItem = [AVPlayerItem playerItemWithURL:vedioURL];
    playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    playerViewController = [[AVPlayerViewController alloc] init];
    playerViewController.player = playVideo;
    playerViewController.player.volume = 20;
    playerViewController.view.frame = self.view.bounds;
    [self.view addSubview:playerViewController.view];
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime:) userInfo:nil repeats:YES];
    [playVideo play];
}


- (void)updateTime:(NSTimer *)timer {
    playerItem = playVideo.currentItem;
    CMTime totalDuration = playerItem.duration;
    NSTimeInterval currentDuration = CMTimeGetSeconds(playerItem.duration);
    NSLog(@" Capturing Duration :%f ",currentDuration);
    CMTime currentTime = playerItem.currentTime;
    int time = ceil(currentTime.value/currentTime.timescale);
    NSLog(@"time : %d",time);
    NSTimeInterval currentTimeNow = CMTimeGetSeconds(playerItem.currentTime);
    NSLog(@" Capturing Current Time :%f ",currentTimeNow);
}



@end

I have video file in my Bundle which name is IMG_0034.MOV

Please see the screenshot of my app and output.

See the play button

enter image description here

One I click the button it plays video below

enter image description here

Finally I print the current time and duration

enter image description here