Search code examples
swiftavplayertvosuser-experience

Can I have AVQueuePlayer and AVPlayer initialised in one singleton?


The question is rather about the concept than request for code example/

In my app I want "play album" feature, and I almost implemented this, however I noticed that user may exit to different album view and e.g. play there a single track there and then going back to previous album queue.

So should I add separate AVPlayer variable inside the same singleton for playing single tracks while leaving song queue intact, or maybe abandon AVPlayer completelely for playing audio and operates only on queues? My first tought is that implement multiple functionality in singleton is bad idea (hence the name).What is the best UX here?

In Apple Music paradigm seems to be treating each album like a playlist and inserting whole new album before rest of the queue.


Solution

  • You can initialize both in a singleton. If you want to keep AVQueuePlayer intact with existing songs queue, then you can create a new object of AVPlayer in the same singleton to play a single request.

    Instead of the above approach, you can use the same AVQueuePlayer with one new list in items array like below

    //Save current player item details
    var currentItem = avQueuePlayer.currentItem
    CMTime currentTime = currentItem.currentTime
    
    //Add new single song at last of queue and play
    var lastItem = avQueuePlayer.items().last
    let newItem = AVPlayerItem(URL: <URL>)
    self.avQueuePlayer?.insert(newItem, after: lastItem)
    lastItem = newItem
    

    As soon as this last song finishes, you can resume saved songs from the queue.

     self.avQueuePlayer.nowPlayingItem = currentItem
    

    I'm just giving one idea. There can be more modifications you need to do.