如何使用AVPlayer addBoundaryTimeObserver?

时间:2018-12-14 14:24:16

标签: swift avplayer

我正在通过单击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

1 个答案:

答案 0 :(得分:1)

根据文档

  

-包含CMTime个值的NSValue对象数组,这些值表示调用块的时间。

您需要创建适当的CMTime结构,然后创建NSValue对象的数组:

let cmtime = CMTime(seconds: 2.18, preferredTimescale: 100)
let cmtimevalue = NSValue(time: cmtime)
let cmtimevalueArray = [cmtimevalue]

请注意,此初始化程序的秒数为Doubletimescale的时间为CMTimeScale,也就是Int32

您的arrayOfBeats不是Array,而是Dictionary,并且字典中的项目没有排序。您可能不会得到想要的订单。

使用元组数组可能会更好。

let arrayOfBeats = [("2.18", 3), ("3.38", 5), ("3.63", 6)]

将您的String秒值转换回Double是您的(琐碎)问题。