Swift:尝试使用UISlider控制AVAudioPlayerNode中的时间 [英] Swift: Trying to control time in AVAudioPlayerNode using UISlider
问题描述
我正在使用连接到 AVAudioEngine
的 AVAudioPlayerNode
播放声音.
I'm using an AVAudioPlayerNode
attached to an AVAudioEngine
to play a sound.
要获取我正在执行的播放器的当前时间:
to get the current time of the player I'm doing this:
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
事件上,我必须将播放器的当前时间更改为滑块中指示的时间.为此:
I have a slider that indicates the current time of the audio. When the user changes the slider value, on .ended
event I have to change the current time of the player to that indicated in the slider.
To do so:
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吗?
However, my function seekTo
is not working correctly(I'm printing currentTime before and after the function and it shows always a negative value ~= -0.02). What is the wrong thing I'm doing and can I find a simpler way to change the currentTime of the player?
推荐答案
我遇到了同样的问题.显然, framestoplay
始终为0,这是由于 sampleRate
导致的.在我的情况下, playerTime.sampleRate
的值始终为0.
I ran into same issue. Apparently the framestoplay
was always 0, which happened because of sampleRate
. The value for playerTime.sampleRate
was always 0 in my case.
所以
let framestoplay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)
必须替换为
let framestoplay = AVAudioFrameCount(Float(sampleRate) * length)
这篇关于Swift:尝试使用UISlider控制AVAudioPlayerNode中的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!