如何在播放过程中改变音频音调? (Swift 4)

How to change audio pitch during playback? (Swift 4)

我想在 Xcode、Swift 4 中使用滑块或变量(即在播放声音时)实时更改某些音频的音调和播放速度.

目前,我正在使用 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上得到答案的。我所要做的就是在 Play() 函数之外声明 pitchspeed 变量,以及 pitch.pitch = speedIncrement * (-500)speed.rate = speedIncrement 表达式。我知道我错过了一些简单的东西...

你想做的事情在这里 link 得到解决:https://www.hackingwithswift.com/example-code/media/how-to-control-the-pitch-and-speed-of-audio-using-avaudioengine 我用过它并且有效。我注意到音高和速度变化很敏感。我将我的设置为:

pitch.pitch -= 0.2
speed.rate -= 0.2