swift - 如何在播放期间更改音频音高? ( swift 4)

标签 swift audio avaudioengine pitch

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

关于swift - 如何在播放期间更改音频音高? ( swift 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100483/

相关文章:

ios - iOS Playground do 方法中的 Json 解析未解析

javascript - 将声音添加到标记数组 - google map javascript

android - 如何在一个 Activity 中停止音乐并在下一个 Activity 中开始另一音乐?

ios - 添加 AKMicrophone 时崩溃

ios - `audioPlayerDidFinishPlaying` 未被调用

ios - AVAudioEngine:一次启动一组 AVAudioPlayerNode

macos - 在浏览器中打开 WebView URL

swift - 将文本添加到导航栏项目

ios - 如何减少 collectionview 中两个单元格之间的垂直空间?

android - 音频流重新录制导致回声