如果使用AVAudioPlayerNode和AVAudioEngine更改音频速率,则会听到失真的声音

时间:2018-06-04 09:27:26

标签: ios swift swift4 avaudioplayer avaudioengine

我想改变音频文件的速率和音高。当我改变音频音调的速率自动改变并且听不到清晰的音频声时。

我正在使用此代码

var engine: AVAudioEngine!
var player: AVAudioPlayerNode!
var pitch : AVAudioUnitTimePitch!
var file = AVAudioFile()
var totalDuration : TimeInterval!


 func configurePlayer() {
        engine = AVAudioEngine()
        player = AVAudioPlayerNode()
        player.volume = 1.0

        let path = Bundle.main.path(forResource: "sample", ofType: "wav") 
        let url = URL.init(fileURLWithPath: path!) 

        file = try! AVAudioFile(forReading: url)
        let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))
        do {
            try file.read(into: buffer!)
        } catch _ {
        }

        pitch = AVAudioUnitTimePitch()

        pitch.rate = 1

        engine.attach(player)

        engine.attach(pitch)
        engine.attach(speedEffect)


        engine.connect(player, to: pitch, format: buffer?.format)

        engine.connect(pitch, to: engine.mainMixerNode, format: buffer?.format)

        player.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)

        engine.prepare()
        do {
            try engine.start()
        } catch _ {
        }
    }




@IBAction func slideValueChanged(_ sender: UISlider) {

        let newRate = sender.value/120;
        pitch.rate = newRate
    }

使用滑块改变速率时声音变坏。

 slider minValue: 60  maxValue: 240

0 个答案:

没有答案