我用一个视图启动了一个新项目,并将此代码添加到视图控制器中:
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *videoURL;
videoURL = [NSURL URLWithString:@"https://s3.amazonaws.com/xxxxxx.mp4"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self
forKeyPath:@"status"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:@"AVPlayerStatus"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (context == @"AVPlayerStatus") {
NSLog(@"AVPlayerStatus changed");
if ([object isKindOfClass:[AVPlayerItem class]] && [keyPath isEqualToString:@"status"]) {
NSLog(@"Ready to play");
}
else if (((AVPlayerItem *)object).status == AVPlayerStatusFailed) {
NSLog(@"Failed to Ready");
}
else if (((AVPlayerItem *)object).status == AVPlayerStatusUnknown) {
NSLog(@"Not known");
}
}
}
输出结果为:
2016-06-21 19:57:56.911 VideoTest[5740:1334235] AVPlayerStatus changed
2016-06-21 19:57:56.911 VideoTest[5740:1334235] Not known
为什么AVPlayerItem没有加载?以及如何加载?
答案 0 :(得分:2)
这是一个远程资产(它位于大型互联网上的某个地方)。在您尝试播放之前,它没有任何有意义的状态;在那时,我们开始加载资产并探索其性质。你没有尝试过它,所以状态只是在Unknown。
为什么AVPlayerItem没有加载?以及如何加载?
您可以通过播放资源来加载项目。
您的代码在三个方面存在缺陷:
您的第一个条件从不测试状态是否为ReadyToPlay;
您永远不会尝试播放资产。
您使用的是context
错误。
我测试了你的代码,但是这样编辑,修复了所有这三件事:
@interface ViewController ()
@property AVPlayer* player;
@end
@implementation ViewController
- (IBAction)doLoad:(id)sender {
NSURL *videoURL;
videoURL = [NSURL URLWithString:@"https://s3.amazonaws.com/lookvideos.mp4/t/05093dabec6c9448f7058a4a08f998155b03cc41.mp4"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self
forKeyPath:@"status"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:nil];
self.player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
[self.player play];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
NSLog(@"AVPlayerStatus changed");
if (((AVPlayerItem *)object).status == AVPlayerStatusReadyToPlay) {
NSLog(@"Ready to play");
}
else if (((AVPlayerItem *)object).status == AVPlayerStatusFailed) {
NSLog(@"Failed to Ready");
}
else if (((AVPlayerItem *)object).status == AVPlayerStatusUnknown) {
NSLog(@"Not known");
}
}
@end
起初我在控制台中看到“未知”,但是一旦我尝试播放资产,它就会变为“准备播放”。