我希望在 Xcode、Swift 4 中使用 slider 或变量(即在播放声音时)实时更改某些音频的音高和播放速度。
目前,我正在使用 AVAudioEngine,它允许我在播放开始之前设置这些值,但在实际播放音频时我无法更改它们。
这是有问题的代码:
func Play() {
engine = AVAudioEngine()
audioPlayer = AVAudioPlayerNode()
audioPlayer.volume = 1.0
let path = Bundle.main.path(forResource: "filename", ofType: "mp3")!
let url = NSURL.fileURL(withPath: path)
let file = try? AVAudioFile(forReading: url)
let buffer = AVAudioPCMBuffer(pcmFormat: file!.processingFormat, frameCapacity: AVAudioFrameCount(file!.length))
do {
try file!.read(into: buffer!)
} catch _ {
}
let pitch = AVAudioUnitTimePitch()
let speed = AVAudioUnitVarispeed()
pitch.pitch = speedIncrement * (-500)
speed.rate = speedIncrement
engine.attach(audioPlayer)
engine.attach(pitch)
engine.attach(speed)
engine.connect(audioPlayer, to: speed, format: buffer?.format)
engine.connect(speed, to: pitch, format: buffer?.format)
engine.connect(pitch, to: engine.mainMixerNode, format: buffer?.format)
audioPlayer.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
engine.prepare()
do {
try engine.start()
} catch _ {
}
audioPlayer.play()
}
这甚至可以使用 AVAudioEngine 吗?
如果 AVAudioEngine 无法做到这一点,还有哪些其他可能的解决方案?
最佳答案
实际上,我从reddit得到了答案。我所要做的就是声明 pitch
和 speed
Play()
之外的变量函数,以及 pitch.pitch = speedIncrement * (-500)
和 speed.rate = speedIncrement
表达式。我知道我错过了一些简单的东西......
关于swift - 如何在播放期间更改音频音高? ( swift 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100483/