I am using AVPlayer to play audio from a URL
In ViewDidLoad:
self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:imageText]];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
[player addObserver:self forKeyPath:@"status" options:0 context:nil];
[player play];
Observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (object == player && [keyPath isEqualToString:@"status"]) {
if (player.status == AVPlayerStatusReadyToPlay) {
//[playingLbl setText:@"Playing Audio"];
NSLog(@"fineee");
[playBtn setEnabled:YES];
} else if (player.status == AVPlayerStatusFailed) {
// something went wrong. player.error should contain some information
NSLog(@"not fineee");
NSLog(@"%@",player.error);
}
else if (player.status == AVPlayerItemStatusUnknown) {
NSLog(@"AVPlayer Unknown");
}
}
}
but the player sometimes is stuck and does not play the audio but then also status is AVPlayerStatusReadyToPlay. It never goes inside AVPlayerStatusFailed or AVPlayerItemStatusUnknown. As i want to handle AVPlayer's error, it must go inside these as well. Please help!!
You should observe CurrentItem's status. AVPlayer failed because of AVPlayerItem failed, if anythings went wrong, it begins from AVPlayerItem then AVPlayer.
try:
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
in your observeValueForKeyPath:
if (object == audioPlayer.currentItem && [keyPath isEqualToString:@"status"]) {
if (audioPlayer.currentItem.status == AVPlayerItemStatusFailed) {
NSLog(@"------player item failed:%@",audioPlayer.currentItem.error);
}
}
You can take a look of AVPlayer's handling or use it directly from HysteriaPlayer, my open source project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With