I been searching everywhere and I still can't find a solution to this problem. I have a AVQueuePlayer
for a radio app that I am making. It has about 20 AVPlayerItems
queued at a time. I added the AVPlayerItemDidPlayToEndTimeNotification
observer to each one of those items. The notification gets fired and executes the code to remove key observers for metadata and status so it doesn't crash and advances to next item in the queue. However it doesn't want to play. There is no error, the status is ready to play, the AVPlayer
URL is loaded perfectly. If I click the button to call the advancenextitem it works perfectly and plays perfectly too.
Now the strangest thing is: if I post the notification manually the notification code works perfectly. I would be grateful for any help or input as I been trying everything to get this working.
if (playlist != nil) {
playlistInterval = [playlist count]/4.0;
NSMutableArray *playerItems = [[NSMutableArray alloc] initWithCapacity:playlistInterval];
for(int i = 0; i < playlistInterval; i++) {
NSString *tempString = [playlist objectAtIndex:i];
//NSLog(@"%@", tempString);
NSURL *temp = [[NSURL alloc] initWithString:tempString];
AVPlayerItem *itemTemp = [AVPlayerItem playerItemWithURL:temp];
[itemTemp addObserver:self forKeyPath:@"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
[itemTemp addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(playerItemDidReachEnd:)
name: AVPlayerItemDidPlayToEndTimeNotification
object: itemTemp];
[playerItems addObject:itemTemp];
playlistCounter++;
}
qPlayer = [AVQueuePlayer queuePlayerWithItems:playerItems];
qPlayer.actionAtItemEnd = AVPlayerActionAtItemEndAdvance;
[ qPlayer addObserver:self
forKeyPath:@"rate"
options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
context:rateDidChangeKVO];
[qPlayer addObserver:self forKeyPath:@"currentItem.duration"
options:0
context:durationDidChangeKVO];
return YES;
}
return NO;
}
- (IBAction)advancePlayer:(id)sender {
unsigned long size = [[qPlayer items] count];
NSLog(@"%tu",size);
if (size <= 0) {
[self initializePlayerWithItems:currentKey];
[qPlayer play];
} else {
//NSLog(@"%@",[qPlayer currentItem]);
[[qPlayer currentItem] removeObserver:self forKeyPath:@"status"];
[[qPlayer currentItem] removeObserver:self forKeyPath:@"timedMetadata"];
[qPlayer advanceToNextItem];
[qPlayer play];
}
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
[self advancePlayer:nil];
NSLog(@"IT REACHED THE END");
}
Now if I call this everything works perfectly from a button or something:
[[NSNotificationCenter defaultCenter]
postNotificationName:@"AVPlayerItemDidPlayToEndTimeNotification"
object:[qPlayer currentItem]];