我正在使用AVAudioPlayerNode
附加到一个AVAudioEngine
来播放声音。
要获得我正在这样做的玩家的当前时间:
extension AVAudioPlayerNode {
var currentTime: TimeInterval {
get {
if let nodeTime: AVAudioTime = self.lastRenderTime, let playerTime: AVAudioTime = self.playerTime(forNodeTime: nodeTime) {
return Double(playerTime.sampleTime) / playerTime.sampleRate
}
return 0
}
}
}
我有一个滑块,指示音频的当前时间。当用户更改滑块值时,.ended
我必须将播放器的当前时间更改为滑块中指示的时间。为此:
extension AVAudioPlayerNode {
func seekTo(value: Float, audioFile: AVAudioFile, duration: Float) {
if let nodetime = self.lastRenderTime{
let playerTime: AVAudioTime = self.playerTime(forNodeTime: nodetime)!
let sampleRate = self.outputFormat(forBus: 0).sampleRate
let newsampletime = AVAudioFramePosition(Int(sampleRate * Double(value)))
let length = duration - value
let framestoplay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)
self.stop()
if framestoplay > 1000 {
self.scheduleSegment(audioFile, startingFrame: newsampletime, frameCount: framestoplay, at: nil,completionHandler: nil)
}
}
self.play()
}
但是,我的函数seekTo
无法正常工作(我在函数之前和之后打印 currentTime,它始终显示负值 ~= -0.02)。我做错了什么,我能找到一种更简单的方法来更改播放器的 currentTime 吗?