如何在使用 AVPlayer 从数组中选择后播放下一首曲目
How to make play the next track after selected from array with AVPlayer
我想制作一个音频播放器。我从设备的本地目录中获取曲目,并将它们放入类型为 [AVPlayerItem] 的数组“playerQueue”中。 TableView 是用多行轨道创建的。我想点击任何行,曲目应该播放 - 它有效。当前曲目结束后,应自动开始播放下一首曲目。但我做不到。此外,我无法使用 AVQueuePlayer 执行此操作 - 播放列表从头开始播放。现在我的代码如下所示:
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()
}
您可以使用 Key-Value Observer 或 Notification Center 来控制 playerItem,例如:音量、持续时间、搜索……
示例:
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
}
}
我想制作一个音频播放器。我从设备的本地目录中获取曲目,并将它们放入类型为 [AVPlayerItem] 的数组“playerQueue”中。 TableView 是用多行轨道创建的。我想点击任何行,曲目应该播放 - 它有效。当前曲目结束后,应自动开始播放下一首曲目。但我做不到。此外,我无法使用 AVQueuePlayer 执行此操作 - 播放列表从头开始播放。现在我的代码如下所示:
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()
}
您可以使用 Key-Value Observer 或 Notification Center 来控制 playerItem,例如:音量、持续时间、搜索……
示例:
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
}
}