Search code examples
iosavplayeravqueueplayer

Possible to insert item at top of queue using AVQueuePlayer?


Assuming the queue has already been initialized, the only method I see to add items into the queue is:

- (void)insertItem:(AVPlayerItem *)item afterItem:(AVPlayerItem *)afterItem

The documentation says Pass nil to append the item to the queue.

So then is it not possible to add an item into the top of the queue? I want to be able to replay what was previously played without removing and requeueing everything up again.


Solution

  • Larme's comment above got me thinking and I was actually able to mimic the behavior I was looking for by doing the following:

    // pause the player since we're messing with the currently playing item
    [_avQueuePlayer pause];
    
    // get current first item
    id firstItem = [_avQueuePlayer.items objectAtIndex:0];
    
    // add new item in 2nd spot
    [_avQueuePlayer insertItem:newItem afterItem:firstItem];
    
    // remove our first item so the new item becomes first in line
    [_avQueuePlayer removeItem:firstItem];
    
    // now add the original first item back in after the newly insert item
    [_avQueuePlayer insertItem:firstItem afterItem:newItem];
    
    // continue playing again
    [_avQueuePlayer play];
    

    This worked great! I think the only downside is the player has to buffer again the next item which we removed and inserted back in. However the remaining items in the queue will stay buffered so that's better than having to reset the entire queue.