gpt4 book ai didi

ios - 如何将新项目添加到当前正在播放旧项目的 AVQueuePlayer

转载 作者:行者123 更新时间:2023-11-28 05:55:12 27 4
gpt4 key购买 nike

将新项目添加到 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)
}
}
}

最佳答案

您正在使用一些项目初始化 AVQuePlayer,这些项目是 AVQuePlayer 的基本副本,稍后您将新的 AVPlayerItems 附加到您的项目数组,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
}
}

尝试并分享结果。

关于ios - 如何将新项目添加到当前正在播放旧项目的 AVQueuePlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51667715/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com