如何在播放期间更改音频音高? (斯威夫特4)

时间:2018-03-04 21:07:05

标签: swift audio avaudioengine pitch

我希望在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无法做到这一点,还有哪些其他可能的解决方案?

2 个答案:

答案 0 :(得分:0)

实际上,我从reddit得到了答案。我所要做的就是在Q函数之外声明pitchspeed变量,以及Play()pitch.pitch = speedIncrement * (-500)表达式。我知道我错过了一些简单的事情......

答案 1 :(得分:0)

您要执行的操作已在以下链接上得到解决: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