我在使用AVPlayer
開始播放外部視頻(通過互聯網)時遇到了一些問題。請在建議解決方案之前閱讀該問題。 我初始化播放器這樣的:如何在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
的state
,然後我打電話[player play]
。發生這種情況時,rate
更改爲1.00000
,這意味着它實際上正在以此速率播放,但視頻現在只是開始緩衝而不是播放。屏幕是黑色的,需要幾秒鐘,然後然後它開始播放。但是,費率表明它在開始播放之前就開始播放。費率保持在1.00000
,而不是開始緩衝時下降到0
,這使我很難知道玩家何時有足夠的信息來開始設置控制(I.E時間戳等)。上述
的NSLog()
打印出視頻的持續時間打印出nan
(非數字),這使我想到,該項目還沒有準備好進行播放,但是,速度停留在1.0000
直到它緩衝一段時間後,它實際上會發揮,仍然在1.0000
率。
但是,它會被調用兩次。 rate
「更改」爲1.0000
兩次而不是介於兩者之間的其他任何東西。在兩次通話中,視頻的持續時間都是可用變量。
我的目標是儘快獲取視頻的當前時間戳和總時間戳(I.E 0:00/3:52
)。這也將用於註冊滑塊的清理(用於快進等)。
當玩家通知我它的播放速度爲1.0000
兩次時,這些值還沒有準備好。如果我在一秒鐘左右手動點擊「播放」(並致電[player play]
),那麼它正在工作。我該如何註冊才能知道視頻何時準備好,而不僅僅是「準備就緒」?
你有沒有找到任何解決辦法?我有同樣的問題... –
@RubenMartinezJr。不,我從來沒有完成這個應用程序,但我幾個星期後再次開始!如果我偶然發現並解決問題,我會盡力記住通知您。 – Sti
非常感謝! –