如何在特定时间停止AVPlayer?

时间:2016-06-30 07:29:22

标签: ios iphone avplayer avplayerviewcontroller avplayeritem

我的代码:

    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];

这里我会在特定时间停止播放视频。

2 个答案:

答案 0 :(得分:4)

你要做的是:

在.h文件中创建以下属性:

@property (strong) id playerObserver;

在.m文件中添加此代码:

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];
}];

此代码将跟踪视频何时开始播放。然后,在你想要的任何时间(这里3秒)之后,它将暂停播放器。至少,我们删除了播放器上的观察者。

希望这有帮助!

答案 1 :(得分:0)

SWFIT 3版来自@Anthonin C的答案。

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