我正在通过单击UI中的按钮来手动记录歌曲的拍数。
此后,我想在每次arrayOfBeats的键与addBoundaryTimeObserver
匹配时再次调用playerItem.currentTime
播放歌曲
如何将arrayOfBeats
的键提供给addBoundaryTimeObserver
方法?
//save the time as a string with 2 decimal places
let timeString = String(format: "%.2f", strongSelf.timeInSeconds)
let arrayOfBeats = ["2.18": 3, "3.38": 5, "3.63": 6] // x.y seconds : beatCount
var timeObserverToken:Any!
func addBoundaryTimeObserver(url: URL) {
let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
// Build boundary times from arrayOfBeats keys
let keys = arrayOfBeats.keys.compactMap {$0}
// how can I convert keys to to NSValue as in https://developer.apple.com/documentation/avfoundation/avplayer/1388027-addboundarytimeobserver
var times = [NSValue]()
let mainQueue = DispatchQueue.main
player?.play()
timeObserverToken =
player?.addBoundaryTimeObserver(forTimes: times, queue: mainQueue) {
//update label with beatCount every time duration of audio file is transversed and it matches an element in var times = [NSValue]()
}
}//end addBoundaryTimeObserver
答案 0 :(得分:1)
根据文档
次-包含
CMTime
个值的NSValue对象数组,这些值表示调用块的时间。
您需要创建适当的CMTime
结构,然后创建NSValue
对象的数组:
let cmtime = CMTime(seconds: 2.18, preferredTimescale: 100)
let cmtimevalue = NSValue(time: cmtime)
let cmtimevalueArray = [cmtimevalue]
请注意,此初始化程序的秒数为Double
,timescale
的时间为CMTimeScale
,也就是Int32
您的arrayOfBeats
不是Array
,而是Dictionary
,并且字典中的项目没有排序。您可能不会得到想要的订单。
使用元组数组可能会更好。
let arrayOfBeats = [("2.18", 3), ("3.38", 5), ("3.63", 6)]
将您的String
秒值转换回Double
是您的(琐碎)问题。