我在TableView中有一个音频网址列表,所以每当我点击didSelectRowAt
上的每个单元格时,都会调用此方法
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Prepare Audio URL
let audioUrl = URL(string: (channelSelected.audioUrl?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed))!)
let playerItem = AVPlayerItem(url: audioUrl!)
playerItem.addObserver(self, forKeyPath: "timedMetadata", options: .new, context: nil)
player = AVPlayer(playerItem: playerItem)
playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true, completion: {
self.playerViewController.player?.play()
})
}
根据教程,我实现了观察值监听器
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("keypath = \(keyPath!)")
let avPlayerItem: AVPlayerItem = object as! AVPlayerItem
if let timedMetadata = avPlayerItem.timedMetadata {
print("Timed metadata = \(timedMetadata)")
} else {
print("Timed metadata nil")
}
}
问题在于timedMetadata
始终为零。帮助将不胜感激。
答案 0 :(得分:10)
您的代码运行正常,此问题的原因是由服务器端的问题引起的。
您可以使用此工具mp3tag编辑音频文件 - 添加元数据标记并将其上传到服务器。
例如,您可以尝试这些音频包含元数据标签:
http://ice1.somafm.com/groovesalad-128-mp3
https://developer.jwplayer.com/jw-player/demos/basic/audio-metadata/assets/index.m3u8
要确认,上述文件应该可以正常使用您的代码。
答案 1 :(得分:1)
这是另一种选择,因为我发现服务器没有使用“定时元数据”。对于那些没有找到答案的人来说,这就是我们最终实施的方式。后端正在使用Wowza Server。
let playerItem = AVPlayerItem(url: audioUrl!)
let adID = AVMetadataItem.identifier(forKey: "X-TITLE", keySpace: .hlsDateRange)
let metadataCollector = AVPlayerItemMetadataCollector(identifiers: [adID!.rawValue], classifyingLabels: nil)
metadataCollector.setDelegate(self, queue: DispatchQueue.main)
playerItem.add(metadataCollector)
然后声明AVPlayerItemMetadataCollectorPushDelegate
func metadataCollector(_ metadataCollector: AVPlayerItemMetadataCollector, didCollect metadataGroups: [AVDateRangeMetadataGroup], indexesOfNewGroups: IndexSet, indexesOfModifiedGroups: IndexSet) {
for metadataGroup in metadataGroups {
for metadata in metadataGroup.items {
}
}
}