bibscy
bibscy

Reputation: 2708

How to use AVPlayer addBoundaryTimeObserver?

I am recording the beat count of a song manually, by tapping on a button in the UI.

After that, I want to play the song again call addBoundaryTimeObserver every time the keys of arrayOfBeats match the playerItem.currentTime

How can I feed the keys of arrayOfBeats to addBoundaryTimeObserver method?

   //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

Upvotes: 0

Views: 1962

Answers (1)

Warren Burton
Warren Burton

Reputation: 17382

As per the docs

times - An array of NSValue objects containing CMTime values representing the times at which to invoke block.

You need to create appropriate CMTime structs then create an array of NSValue objects:

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

Be aware that the seconds for this initialiser is Double and timescale is CMTimeScale aka Int32

Also your arrayOfBeats is not an Array, it's a Dictionary and items in dictionaries are NOT ordered. You probably won't get the order you were looking for.

You might be better served with an array of tuples.

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

Converting your String seconds value back to Double is your (trivial) problem.

Upvotes: 4

Related Questions