2

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()
    }
VyacheslavB
  • 181
  • 9

1 Answers1

4

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
        }
    }
HHumorous
  • 174
  • 1
  • 11
  • Sorry, but it doesn't work if I use let player:AVPlayer = { let avPlayer = AVPlayer() avPlayer.automaticallyWaitsToMinimizeStalling = false return avPlayer }() player.replaceCurrentItem(with: playerItem) // playerItem is AVPlayerItem Maybe you know how fix it? – VyacheslavB Jul 31 '20 at 13:10
  • Try this source code [https://github.com/oCanKhacNguyen/videoPlayerDemo](https://github.com/oCanKhacNguyen/videoPlayerDemo). It may be helpful for you – HHumorous Aug 03 '20 at 02:49