How to change audio pitch during playback? (Swift

2020-07-22 16:33发布

问题:

I'm looking to change the pitch and playback speed of some audio in real time with a slider, or a variable (i.e. while the sound is playing) in Xcode, Swift 4.

Currently, I'm using AVAudioEngine, which allows me to set these values before playback starts, but I can't change them while I the audio is actually playing.

Here is the code in question:

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()

}

Is this even possible with AVAudioEngine?

If this is not possible with AVAudioEngine, what are other possible solutions?

回答1:

Actually, I got the answer from reddit. All I had to do was to declare the pitch and speed variables outside of the Play() function, along with the pitch.pitch = speedIncrement * (-500) and speed.rate = speedIncrement expressions. I knew I was missing something simple...



回答2:

What you are looking to do is solved here on this link: https://www.hackingwithswift.com/example-code/media/how-to-control-the-pitch-and-speed-of-audio-using-avaudioengine I used it and it works. I have noticed pitch and speed changes are sensitive. I set mine to:

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