就像我上面解釋的那樣,如果我啓動應用程序並首先關閉wifi,然後嘗試用AVPlayer
播放音樂,我將收到一個AVPlayerItemStatusFailed
,但之後,即使再次打開wifi,我也不能再收到任何KVO callback
。AVPlayer第一次失敗後,我再也無法收到KVO回撥
在其他情況下,如果我運行應用程序,並率先開啓WiFi和打法,我可以收到AVPlayerItemStatusReadyToPlay
,之後,我可以繼續接收KVO callback
即使我打開wifi關閉...
那麼如何解決第一種情況?
@interface ViewController()
@property (strong, nonatomic) AVPlayer *player;
@property (assign, nonatomic) NSInteger index;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)buttonPressed:(UIButton *)sender {
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
NSLog(@"removed %@", self.player.currentItem);
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.urls[self.index]]];
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
NSLog(@"added %@", item);
[self.player replaceCurrentItemWithPlayerItem:item];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"status"]) {
if ([object isMemberOfClass:[AVPlayerItem class]]) {
AVPlayerItem *playerItem = (AVPlayerItem *)object;
switch (playerItem.status) {
case AVPlayerItemStatusFailed:
NSLog(@"failed");
break;
case AVPlayerItemStatusReadyToPlay:
NSLog(@"ready");
break;
case AVPlayerItemStatusUnknown:
NSLog(@"unknown");
break;
}
}
}
}
- (AVPlayer *)player {
if (!_player) {
_player = [[AVPlayer alloc] init];
}
return _player;
}
- (NSArray *)urls {
return @[@"https://of92d29bn.qnssl.com/record1.m4a", @"https://of92d29bn.qnssl.com/record2.m4a"];
}
- (NSInteger)index {
if (_index == 0) {
_index = 1;
} else {
_index = 0;
}
return _index;
}
這是我所有的代碼。
更常見的是,我發現如果avplayer播放了第一個項目並失敗了,它將不能再播放任何其他項目!有誰知道爲什麼? – wkx