AVAudioEngine寻找这首歌的时间 [英] AVAudioEngine seek the time of the song
问题描述
我正在使用 AVAudioPlayerNode
播放一首歌,我正在尝试使用 UISlider
控制时间,但我可以弄清楚如何使用 AVAUdioEngine
来寻找时间。
I am playing a song using AVAudioPlayerNode
and I am trying to control its time using a UISlider
but I can't figure it out how to seek the time using AVAUdioEngine
.
推荐答案
经过多次尝试和错误后,我想我终于弄明白了。
After MUCH trial and error I think I have finally figured this out.
首先,您需要计算文件的采样率。为此,请获取AudioNode的最后渲染时间:
First you need to calculate the sample rate of your file. To do this get the last render time of your AudioNode:
var nodetime: AVAudioTime = self.playerNode.lastRenderTime
var playerTime: AVAudioTime = self.playerNode.playerTimeForNodeTime(nodetime)
var sampleRate = playerTime.sampleRate
然后,将采样率乘以新的时间(以秒为单位)。这将为您提供想要启动播放器的歌曲的确切帧:
Then, multiply your sample rate by the new time in seconds. This will give you the exact frame of the song at which you want to start the player:
var newsampletime = AVAudioFramePosition(sampleRate * Double(Slider.value))
接下来,您将要计算那里的帧数保留在音频文件中:
Next, you are going to want to calculate the amount of frames there are left in the audio file:
var length = Float(songDuration!) - Slider.value
var framestoplay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)
最后,停止节点,安排新段音频,并再次启动你的节点!
Finally, stop your node, schedule the new segment of audio, and start your node again!
playerNode.stop()
if framestoplay > 1000 {
playerNode.scheduleSegment(audioFile, startingFrame: newsampletime, frameCount: framestoplay, atTime: nil,completionHandler: nil)
}
playerNode.play()
如果您需要进一步解释,我在这里写了一个简短的教程: http://swiftexplained.com/?p=9
If you need further explanation I wrote a short tutorial here: http://swiftexplained.com/?p=9
这篇关于AVAudioEngine寻找这首歌的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!