How to make play the next track after selected from array with AVPlayer

Viewed 360

I want to create an audio player. I get the tracks from the local directory of the device and put them to the array "playerQueue" with type [AVPlayerItem]. TableView was created with rows of tracks. I want to tap on any row and track should plays - it works. After the end of current track, playback of the next track should begin automatically. But I can’t do it. Also, I can’t do this with AVQueuePlayer - the playlist starts playing from the very beginning. Now my code looks like this:

class TableViewController: UITableViewController {
...
    var player: AVPlayer!
    var playerQueue: [AVPlayerItem] = []
...
//Creating playerQueue from directory
private func createPlayerQueue(with content: [String], from directory: String?) -> [AVPlayerItem] {
        var playerQueue: [AVPlayerItem] = []
        content.forEach { (url) in
            let fileUrl = directory! + "/" + url
            let asset = AVAsset(url: URL(fileURLWithPath: fileUrl))
            let item = AVPlayerItem(asset: asset)
            playerQueue.append(item)
        }
        return playerQueue
    }
....
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let fullPath: String = currentDirectory! + "/" + content[indexPath.row]

                playerQueue = createPlayerQueue(with: content, from: currentDirectory)
                let currentItem = playerQueue[indexPath.row]
                player = AVPlayer(playerItem: currentItem)
                player.play()
    }
1 Answers

You can use Key-Value Observer or Notification Center to control playerItem like: Volume, Duration time, Seeking, ...

Example:

 NotificationCenter.default.addObserver(self, selector: #selector(itemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)

@objc func itemDidPlayToEndTime(notification: Notification) {
        if (notification.object as? AVPlayerItem) == self.player.currentItem {
            // Play next item in your queue
        }
    }
Related