如何将新项目添加到当前正在与旧项目一起播放的AVQueuePlayer中

时间:2018-08-03 07:47:38

标签: ios swift avfoundation avqueueplayer

无法向AVQueuePlayer添加新项目

在某些情况下,我正在从服务器流式传输HLS音频。最初,我制作一个AVPlayerItem数组。并初始化AVQueuePlayer,然后单击按钮,它可以很好地播放初始项目。但是当我一半的物品播放完毕时,我试图在列表末尾添加更多无法播放的物品。

class ViewController: UIViewController, AVAudioPlayerDelegate{

let baseUrl = "********"

var player: AVQueuePlayer?
var items: [AVPlayerItem] = [];

let controller = AVPlayerViewController()

var counter = 0;

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(animationDidFinish(_:)),
                                           name: .AVPlayerItemDidPlayToEndTime,
                                           object: player?.items())
}

override func viewDidAppear(_ animated: Bool) {
    queueMaker()
}

@IBAction func btnTapped(_ sender: UIButton) {

    let player = AVQueuePlayer(items: self.items)
    let playerLayer = AVPlayerLayer(player: player)
    self.view.layer.addSublayer(playerLayer)
    player.play()    
}

@objc func animationDidFinish(_ notification: NSNotification) {
    print("HLS : AVQueuePlayer Item Finished Playing")
    counter += 1
    if ((items.count) - counter) < 4 {
        print("HLS : Adding More Items")
        addMoreItemsToQueue()
    }
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

func queueMaker() {

    let listOfAyahs: [String] = ["1/1.m3u8","2/2.m3u8","3/3.m3u8","4/4.m3u8","5/5.m3u8","6/6.m3u8","7/7.m3u8"]

    for item in listOfAyahs {
        let stringUrl = "\(self.baseUrl)\(item)"
        let url = URL(string: stringUrl)
        let item = AVPlayerItem(url: url!)
        items.append(item)
    }
}


func addMoreItemsToQueue() {

    let listOfAyahs: [String] = ["8/8.m3u8","9/9.m3u8","10/10.m3u8","11/11.m3u8","12/12.m3u8","13/13.m3u8","14/14.m3u8"]

    for item in listOfAyahs {
        let stringUrl = "\(self.baseUrl)\(item)"
        let url = URL(string: stringUrl)
        let item = AVPlayerItem(url: url!)
        items.append(item)
    }
  }
}    

1 个答案:

答案 0 :(得分:1)

您正在初始化带有某些项目的AVQuePlayer,这是AVQuePlayer的基本副本,随后您将新的AVPlayerItems追加到您的items数组中,而AVQuePlayer对此并不了解。因此,更新以下内容使其正常工作。

@IBAction func btnTapped(_ sender: UIButton) {
    // UPDATE THE PLAYER's SCOPE TO GLOBAL
    player = AVQueuePlayer(items: self.items)
    let playerLayer = AVPlayerLayer(player: player)
    self.view.layer.addSublayer(playerLayer)
    player?.play()
}

然后将替换插入项添加到队列中

func addMoreItemsToQueue() {

  let listOfAyahs: [String] = ["8/8.m3u8","9/9.m3u8","10/10.m3u8","11/11.m3u8","12/12.m3u8","13/13.m3u8","14/14.m3u8"]

  var lastItem = self.player?.items().last
  for item in listOfAyahs {
        let stringUrl = "\(self.baseUrl)\(item)"
        let url = URL(string: stringUrl)
        let item = AVPlayerItem(url: url!)
        self.player?.insert(item, after: lastItem)
        lastItem = item
    }
}

尝试并分享结果。