addPeriodicTimeObserver is not called every millisecond?

半城伤御伤魂 提交于 2019-12-11 15:49:05

问题


I know that player.currentItem.currentTime().seconds returns the current time in seconds of the audio file that is being played.

Can I add a callback function on player to be called every millisecond?
For example for second 1, this callBack function should be called 1000 times.

The problem is that using addPeriodicTimeObserver the callBack function is called only 1 time per second, rather than 1000 times per second.

Why do I need this?

1.
I am extracting the beat count of a Salsa song manually by tapping on a button in the UI while the audio file is being played and I record it as [Int:Int] // milisecondButtonTapped: beatCount.

My array is going to look like
var beatCounts = [982: 1, 2051: 2, 3006: 3, 5027: 5, 6011: 6, 7028: 7]

After the audio finishes playing I will end up with an array containing the beatCounts corresponding to certain milliseconds of player.currentItem.currentTime()

2.

Now, I want to play the song again and check if player currentTime in milliseconds is == to one of the values in var beatCounts

func checkCurrentTime(playerTimeMilliseconds: Int) {

  for (millisecond, beatCount) in beatCounts {
    if  playerTimeMilliseconds == millisecond {
       //show beatCount in label on UI 
     }
 }
}





func playSound(url: URL) {

    let playerItem: AVPlayerItem = AVPlayerItem(url: url)
    player = AVPlayer(playerItem: playerItem)


    try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try! AVAudioSession.sharedInstance().setActive(true)
    player?.play()

    player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, 1000), queue: DispatchQueue.main, using: { [weak self] (CMTime) in

        print("cmtime is \(CMTime)")
      CMTime.value

        if self?.player?.currentItem?.status == .readyToPlay {

        }
    })

}//end playSound

来源:https://stackoverflow.com/questions/53704885/addperiodictimeobserver-is-not-called-every-millisecond

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!