gpt4 book ai didi

swift - addPeriodicTimeObserver 不是每毫秒调用一次?

转载 作者:行者123 更新时间:2023-11-30 10:58:15 41 4
gpt4 key购买 nike

我知道 player.currentItem.currentTime().seconds 返回正在播放的音频文件的当前时间(以秒为单位)。

我可以在 player 上添加一个每毫秒调用一次的回调函数吗?
例如,对于第二个 1,该回调函数应被调用 1000 次。

问题是使用 addPeriodicTimeObserver 时,callBack 函数每秒仅调用 1 次,而不是每秒 1000 次。

为什么我需要这个?

1.
我在播放音频文件时通过点击 UI 中的按钮来手动提取 Salsa 歌曲的节拍计数,并将其记录为 [Int:Int]//milisecondButtonTapped:节拍计数。

我的数组看起来像
varbeatCounts = [982:1,2051:2,3006:3,5027:5,6011:6,7028:7]

音频播放完毕后,我将得到一个数组,其中包含与player.currentItem.currentTime()的某些毫秒相对应的beatCounts

2.

现在,我想再次播放这首歌,并检查播放器 currentTime(以毫秒为单位)是否 == 到 varbeatCounts 中的值之一

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

最佳答案

您只需以不同的方式使用 forInterval,而时间单位将为 0.001,并且首选时间缩放应与 NSEC_PER_SEC 一起使用,如下引用

让间隔:CMTime = CMTimeMakeWithSeconds(0.001,preferredTimescale:Int32(NSEC_PER_SEC))

player?.addPeriodicTimeObserver(forInterval: *interval*), queue:
.main) { [weak self] (CMTime) in

关于swift - addPeriodicTimeObserver 不是每毫秒调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704885/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com