ragu
ragu

Reputation: 133

How to stop AVPlayer at specific time?

My code :

    playerController = [[AVPlayerViewController alloc]init];


    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[playerController.player currentItem]];

    playerController.player = [AVPlayer playerWithURL:videoURL];

    playerController.view.frame = self.view.frame;

    [playerController.player seekToTime:kCMTimeZero];

    playerController.player.actionAtItemEnd = AVPlayerActionAtItemEndPause;

    [playerController.player play];

    [self presentViewController:playerController animated:YES completion:nil];

Here I stop the video in specific time.

Upvotes: 1

Views: 4065

Answers (2)

Jerome
Jerome

Reputation: 2152

SWFIT 3 Version come from @Anthonin C 's answer.

player = AVPlayer(url: tmpURL)
player?.perform(#selector(player?.pause), with: nil, afterDelay: 3)

Upvotes: 2

AnthoPak
AnthoPak

Reputation: 4391

What you have to do is :

Create the following property in .h file :

@property (strong) id playerObserver;

Add this code in .m file :

AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]];

[player play];

self.playerObserver = [player addBoundaryTimeObserverForTimes:@[[NSValue valueWithCMTime:CMTimeMake(1, 1000)]] queue:NULL usingBlock:^{
    NSLog(@"Video started playing");

    [player performSelector:@selector(pause) withObject:nil afterDelay:3.0]; //will pause player after 3.0 seconds
    [player removeTimeObserver:self.playerObserver];
}];

This code will track when the video starts playing. Then, after whatever-time you want (here 3 seconds), it will pause the player. At least, we remove the observer on the player.

Hope this helps !

Upvotes: 4

Related Questions