我想在 Swift 中使用 AudioKit 做一个简单的“记录用户的麦克风 -> 应用效果 -> 保存到 wav 文件”链。
下面是我尝试使用的代码。相反,我得到的是通过耳机听到输出(应用了音高效果),但输出文件是空的。我做错了什么?
import AudioKit
import AVFoundation
import SoundpipeAudioKit
class AudioRecorder: ObservableObject {
let engine = AudioEngine()
var recoder: NodeRecorder?
private(set) lazy var outputFileURL: URL = {
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
return documentsPath.appendingPathComponent("recording.wav")
}()
func startRecording() {
do {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Failed to set up recording session.")
return
}
guard let input = engine.input else {
print("No audio input found")
return
}
do {
recorder = try NodeRecorder(node: input, fileDirectoryURL: outputFileURL)
} catch let err {
fatalError("\(err)")
}
let pitchShifter = PitchShifter(input)
engine.output = pitchShifter
do {
try engine.start()
} catch {
print("Unable to start audio engine: \(error.localizedDescription)")
return
}
}
func stopRecording() {
engine.stop()
do {
try AVAudioSession.sharedInstance().setActive(false)
} catch {
print("Failed to stop recording session.")
}
}
}
尝试更改以下内容以使其正常工作:
线
var recoder: NodeRecorder?
更改为 var recorder: NodeRecorder?
// 缺少 r
行
return documentsPath.appendingPathComponent("recording.wav")
更改为return documentsPath
// NodeRecorder需要一个目录,而不是fileDirectoryURL中的文件
在添加录音机之前将
pitchShifter
添加到听力图,因为您要录制移动的音频。
分两个不同步骤录制并保存到 .waf。 NodeRecorder 记录到临时 .caf,然后您可以移动或编码并发送。
进一步查看AudioKit的Cookbook,这个例子会有所帮助:https://github.com/AudioKit/Cookbook/blob/main/Cookbook/CookbookCommon/Sources/CookbookCommon/Recipes/MiniApps/Recorder.swift