如何使用AudioKit保存音频文件?

时间:2018-05-29 17:40:13

标签: ios swift audiokit

我有音频文件。我对它做了一些影响

let pitchshifter = AKPitchShifter(self.audioPlayer)
pitchshifter.shift = 10
AudioKit.output = pitchshifter

如果我在应用程序中播放它,它会起作用,但我想将其保存为新文件,以便以后将其用作avasset。如何实施?

我尝试使用AKNodeRecorder,但这会产生空音轨:

let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("recorded")
let format = AVAudioFormat(commonFormat: .pcmFormatFloat64, sampleRate: 44100, channels: 2, interleaved: false)!
let tape = try! AKAudioFile(forWriting: url, settings: format.settings)
let mixer = AKMixer(self.audioPlayer!, pitchshifter)
AudioKit.output = mixer
self.recorder = try! AKNodeRecorder(node: mixer, file: tape)

try? AudioKit.start()
self.audioPlayer?.play()
self.audioPlayer?.completionHandler = {
    self.recorder?.stop()
    self.selectedAudioURL = tape.url
}

此外,我尝试了renderToFile方法 - 它也无效and I got this error

let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("recorded.m4a")
let format = AVAudioFormat(commonFormat: .pcmFormatFloat64, sampleRate: 44100, channels: 2, interleaved: false)!
let tape = try! AKAudioFile(forWriting: url, settings: format.settings)
try! AudioKit.renderToFile(tape, seconds: Double(CMTimeGetSeconds(self.selectedAudioAsset!.duration)))

我是如何将初始文件添加到AudioKit的:

let audioFile = try AKAudioFile(forReading: audioURL, commonFormat: .pcmFormatFloat32, interleaved: true)
let player = AKPlayer(audioFile: audioFile)
self.audioFile = audioFile
self.audioPlayer = player
player.startTime = self.startTime
AKSettings.defaultToSpeaker = true

提前感谢您的回答!

1 个答案:

答案 0 :(得分:4)

根据我的发现,你必须使用预渲染器来播放"你要记录的内容:

try AudioKit.renderToFile(outputFileForWriting, duration: sequencerTotalSeconds, prerender: {
    self.sequencer.play()
})

但是,对我来说。渲染单个音轨序列会产生窦音。 : - /

希望这有帮助!