Swift -无法在AudioKit中找到简单的“Mic->Effect->File”链

inkz8wg9  于 2024-01-05  发布在  Swift
关注(0)|答案(2)|浏览(91)

我想在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.")
        }
    }
}

字符串

xlpyo6sf

xlpyo6sf1#

尝试更改以下内容以使其工作:
1.行var recoder: NodeRecorder?更改为var recorder: NodeRecorder?//缺少r
1.行return documentsPath.appendingPathComponent("recording.wav")更改为return documentsPath// NodeRecorder需要一个目录,而不是fileDirectoryURL中的文件
1.在添加录音机之前,将pitchShifter添加到听力图中,因为您希望录制转换后的音频。
1.记录和保存到.waf分两个不同的步骤。NodeRecorder记录到一个临时的.caf,然后您可以移动或编码和发送。

  1. NodeRecorder有一些内置的文件管理,小心shouldCleanupRecordings:,因为它默认为true
    --
let pitchShifter = PitchShifter(input)

do {
    recorder = try NodeRecorder(node: pitchShifter, fileDirectoryURL: outputFileURL, shouldCleanupRecordings:false)
} catch let err {
    fatalError("\(err)")
}
engine.output = pitchShifter

字符串
此外,请查看AudioKit的Cookbook,这个例子将有所帮助:https://github.com/AudioKit/Cookbook/blob/main/Cookbook/CookbookCommon/Sources/CookbookCommon/Recipes/MiniApps/Recorder.swift

vcirk6k6

vcirk6k62#

NodeRecorder已连接到输入,但要开始录制,您必须调用record()

do {
    try recorder?.record()
}
catch let error {
    print(error)
}

字符串
通过调用recorder?.stop()停止录音。另外,注意您正在将麦克风输入馈送到NodeRecorder。如果您需要写入音高偏移样本,则必须将pitchShifter馈送到NodeRecorder

recorder = try NodeRecorder(node: pitchShifter, fileDirectoryURL: outputFileURL)

相关问题