我知道player.currentItem.currentTime().seconds
以秒为单位返回正在播放的音频文件的当前时间。
我可以在player
上添加一个回调函数,以便每毫秒调用一次吗?例如对于第二个1,此callBack函数应被调用1000次。
问题是,使用addPeriodicTimeObserver
每秒仅调用1次CallBack函数,而不是每秒调用1000次。
我为什么需要这个?
1。我在播放音频文件时通过单击UI中的按钮来手动提取Salsa歌曲的节奏计数,并将其记录为[Int:Int]
// milisecondButtonTapped:beatCount。
我的数组看起来像var beatCounts = [982: 1, 2051: 2, 3006: 3, 5027: 5, 6011: 6, 7028: 7]
在音频播放完毕后,我将得到一个包含BeatCounts的数组,该数组对应于player.currentItem.currentTime()
的某些毫秒
2。
现在,我想再次播放歌曲,并检查播放器currentTime以毫秒为单位== 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
我知道player.currentItem.currentTime()。seconds返回正在播放的音频文件的当前时间(以秒为单位)。我可以在播放器上添加一个回调函数,以在每个播放器中调用该函数吗?
let interval: CMTime = CMTimeMakeWithSeconds(0.001, preferredTimescale: Int32(NSEC_PER_SEC))
player?.addPeriodicTimeObserver(forInterval: *interval*), queue:
.main) { [weak self] (CMTime) in