2

I have an instance of AVQueuePlayer and I've initialised it with a collection of videos using AVPlayerItem (let's say I have 10 items), On a button event, I need to play the item of nth index from the collection.

I've used - (void)replaceCurrentItemWithPlayerItem:(AVPlayerItem *)item but it replaces the current playing item with the passed AVPlayerItem.

I need to play nth AVPlayerItem of the AVQueuePlayer. Any help will be appreciated.

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
Pradeep Singh
  • 752
  • 1
  • 10
  • 23

2 Answers2

5

Two ideas, not tested:

A. Advancing

NSUInteger indexToPlay = …
AVPlayerItem *currentItem = [queuePlayer currentItem];
NSUInteger currentIndex = [[queuePlayer items] indexOfObject:currentItem];
for (;currentIndex<indexToPlay; currentIndex++)
{
  [queuePlayer advanceToNextItem];
}

B. Calculating the time

Get the duration using -duration (AVPlayerItem) of all videos from the beginning of the queue up to (but not including) the nth video and go to the resulting time with -seekToTime:toleranceBefore:toleranceAfter:.

I think that you should have no problem with tolerance and decoding delay, because the seemed time is the beginning of a video.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
  • Tried B option, but it results in crash as the AVPlayerItem.duration results in NAN coz, its status is not ready yet and hence the player doesn't seek to time and the application crashes. Did tried to observe the status of the current item and then calculate the seek time,but its not working either. – Pradeep Singh Apr 22 '15 at 10:02
  • Option A is bang on. Thanks a lot :) – Pradeep Singh Apr 22 '15 at 10:09
  • this solution will work if the play item is in next of current how about if the item that we want to play is in back ? – Fadi Abuzant Jan 31 '19 at 07:16
  • @FadiAbuzant you might be better off searching for other answers related to playing previous item. There are many here on SO, e.g. [this](https://stackoverflow.com/questions/34971839/better-way-to-do-skip-to-previous-with-avqueueplayer) and [this](https://stackoverflow.com/questions/12176699/skip-to-previous-avplayeritem-on-avqueueplayer-play-selected-item-from-queue/12209586) – superjos Mar 22 '19 at 09:46
3
- (void)playAudioAtIndex:(NSInteger)index
{
    [player removeAllItems];
    for (int i = index; i <playerItems.count; i ++) {
        AVPlayerItem* obj = [playerItems objectAtIndex:i];
        if ([player canInsertItem:obj afterItem:nil]) {
        [obj seekToTime:kCMTimeZero];
        [player insertItem:obj afterItem:nil];
        }
    }
}

playerItems is the NSMutableArray(NSArray) where you store your AVPlayerItems.

Nilesh Patel
  • 6,318
  • 1
  • 26
  • 40