在播放器开始使用AVPlayer播放外部视频(通过互联网)时,我注册了一些麻烦.请在提出解决方案之前阅读该问题.
我像这样初始化玩家:
我像这样初始化玩家:
player = [[AVPlayer alloc] initWithURL:[[NSURL alloc] initWithString:@"http://example.com/video.mp4"]]; playerLayer = [AVPlayerLayer playerLayerWithPlayer:player]; [playerLayer setFrame:[videoView bounds]]; [videoView.layer addSublayer:playerLayer];
这样可以将播放器正确添加到视图中.我添加了以下两行代码来跟踪播放器准备就绪,状态/速率是什么;
[player addObserver:self forKeyPath:@"rate" options:0 context:nil]; [player addObserver:self forKeyPath:@"status" options:0 context:nil];
这两行将调用方法 – (void)observeValueForKeyPath:….当某些内容随AVPlayer的状态或速率而变化时.
到目前为止,它看起来像这样:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //To print out if it is 'rate' or 'status' that has changed: NSLog(@"Changed: %@",keyPath); if ([keyPath isEqualToString:@"rate"]) //If rate has changed: { if ([player rate] != 0) //If it started playing { NSLog(@"Total time: %f",CMTimeGetSeconds([[player currentItem] duration])); // This NSLog is supposed to print out the duration of the video. [self setControls]; // This method (setControls) is supposed to set play/pause-buttons // as well as labels for the current and total time of the current video. } } else if ([keyPath isEqualToString:@"status"]) // If the status changed { if(player.status == AVPlayerStatusReadyToPlay) //If "ReadyToPlay" { NSLog(@"ReadyToPlay"); [player play]; //Start the video } } }
初始化之后,AVPlayer的状态几乎立即改变为readyToPlay,然后调用[player play].当这种情况发生时,速率变为1.00000,这意味着它实际上以这种速度播放,但是视频现在刚刚开始缓冲,而不是播放.屏幕是黑色的,需要几秒钟的时间,然后开始播放.然而,这个比率表明它开始播放之前.速率保持在1.00000,开始缓冲时不下降到0,这使得我很难知道玩家何时有足够的信息来开始设置控件(I.E时间戳等).
打印出上述视频持续时间的NSLog()打印出南(不是数字),这导致我认为该项目没有准备好播放,但是,速率保持在1.0000,直到它缓存一段时间,那么它实际上会玩,还是以1.0000的速度.
然而,它确实被叫了两次.速率“变化”到1.0000两次,而没有任何其他的.在两个呼叫中,视频的持续时间是可用的变量.
我的目标是尽可能快地获取视频的当前和总时间戳(I.E 0:00/3:52).这也将用于注册滑块的滑动(用于快进等).
当玩家通知我以1.0000的速度播放时,这些值尚未准备好,两次.如果我手动点击“播放”一秒钟之后(并呼叫[播放器播放]),那么它的工作.如何注册以了解视频何时准备就绪,而不只是“准备好准备”?
解决方法
来自Apple的AVPlayer和
this example上的
addBoundaryTimeObserverForTimes:queue:usingBlock:.
AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]]; [player play]; // Assumes a property: @property (strong) id playerObserver; // Cannot use kCMTimeZero so instead use a very small period of time self.playerObserver = [player addBoundaryTimeObserverForTimes:@[[NSValue valueWithCMTime:CMTimeMake(1,1000)]] queue:NULL usingBlock:^{ //Playback started [player removeTimeObserver:self.playerObserver]; }];