我正在使用AVAudioPlayerNode
播放一首歌曲,并尝试使用UISlider
控制其时间,但我无法弄清楚如何使用AVAUdioEngine
寻找时间。
我正在使用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
获取采样率。 - hhanesand对于未来的读者,最好获取采样率使用以下代码:
playerNode.outputFormat(forBus: 0).sampleRate
在转换为AVAudioFramePosition时要注意,它是一个整数,而采样率是一个双精度浮点数。如果不对结果进行四舍五入,则可能会得到不良结果。
P.S. 上述答案假设您播放的文件与播放器的输出格式具有相同的采样率,这可能是真实的也可能不是。
playerNode.scheduleSegment()
方法之前调用playerNode.stop()
方法,然后它才会播放。我省略了对playerNode.stop()
的调用,因为我想在指定时间开始播放音轨。哎呀!这真是我的一场灾难!感谢您提供的代码示例! - SouthernYankee65