AVAudioEngine 求歌曲时间

AVAudioEngine seek the time of the song

我正在使用 AVAudioPlayerNode 播放歌曲,我试图使用 UISlider 来控制它的时间,但我不知道如何使用 AVAUdioEngine 来寻找时间.

经过反复试验,我想我终于弄明白了。

首先您需要计算文件的采样率。为此,请获取 AudioNode 的最后渲染时间:

var nodetime: AVAudioTime  = self.playerNode.lastRenderTime
var playerTime: AVAudioTime = self.playerNode.playerTimeForNodeTime(nodetime)
var sampleRate = playerTime.sampleRate

然后,将您的采样率乘以以秒为单位的新时间。这将为您提供您想要启动播放器的歌曲的确切帧数:

var newsampletime = AVAudioFramePosition(sampleRate * Double(Slider.value))

接下来,您要计算音频文件中剩余的帧数:

var length = Float(songDuration!) - Slider.value
var framestoplay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)

最后,停止您的节点,安排新的音频片段,然后再次启动您的节点!

playerNode.stop()

if framestoplay > 1000 {
   playerNode.scheduleSegment(audioFile, startingFrame: newsampletime, frameCount: framestoplay, atTime: nil,completionHandler: nil)
}

playerNode.play()

如果您需要进一步的解释,我在这里写了一个简短的教程:http://swiftexplained.com/?p=9

对于未来的读者,最好将采样率设为:

playerNode.outputFormat(forBus: 0).sampleRate

转换为 AVAudioFramePosition 时也要小心,因为它是一个整数,而采样率是双倍的。如果不对结果进行四舍五入,您可能会得到不理想的结果。

P.S。上面的回答假设你正在播放的文件与播放器的输出格式具有相同的采样率,这可能是正确的也可能不是。