AVPlayer Video SeekToTime

Ganesh picture Ganesh · Jun 13, 2011 · Viewed 23k times · Source

I'm using AVPlayer for play my video using slider and Some Buttons. Here is my methods for moving forward and backward using buttons.

-(IBAction)MoveForward
{
    //int value = timeSlider.value*36000 + 10;
    //CMTime newTime = CMTimeMakeWithSeconds(value, playspeed);
    //CMTime newTime = CMTimeMake(value,(playspeed*timeSlider.maximumValue));

    CMTime newTime = CMTimeMakeWithSeconds(timeSlider.value, playspeed);
    newTime.value += 60;
    [player seekToTime: newTime];
}

-(IBAction)MoveBackward
{
    CMTime newTime = CMTimeMakeWithSeconds(timeSlider.value-1, playspeed);
    [player seekToTime: newTime];
}

My Problem on this is the time to Seek is not working properly. That navigate to next frame based on seconds. I need to move next frame minutely. Help me...

Answer

Samssonart picture Samssonart · Jun 15, 2011

I don't really understand your code, you don't really need separate methods to move forwards and backwards, you can use the same one for both. I've got a working AVPlayer Movie Player, I'll show you how I did the slider part.

-(IBAction)sliding:(id)sender {
    CMTime newTime = CMTimeMakeWithSeconds(seeker.value, 1);
    [self.player seekToTime:newTime];
}

-(void)setSlider {
    sliderTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSlider) userInfo:nil repeats:YES] retain];
    self.seeker.maximumValue = [self durationInSeconds];
    [seeker addTarget:self action:@selector(sliding:) forControlEvents:UIControlEventValueChanged];
    seeker.minimumValue = 0.0;
    seeker.continuous = YES;  
}

- (void)updateSlider {
    self.seeker.maximumValue = [self durationInSeconds];
    self.seeker.value = [self currentTimeInSeconds];
}

- (Float64)durationInSeconds {
    Float64 dur = CMTimeGetSeconds(duration);
    return dur;
}

- (Float64)currentTimeInSeconds {
    Float64 dur = CMTimeGetSeconds([self.player currentTime]);
    return dur;
}

And that's it, there are two gotchas in this code, first, the duration property returns a CMTime variable, you have to convert it to a float, also, this returns the raw number of seconds, you have to convert it to h:mm:ss if you want to display time labels. Second, the updateSlider method is triggered by a timer every second. Good Luck.