Swift 使用蓝牙麦克风的 installTap 产生 "chipmunk" 音频

Swift installTap using bluetooth mic produces "chipmunk" audio

当使用蓝牙麦克风并记录 installTap 的输出时,我得到了高音调、非常快的播放。

使用蓝牙:

installTap -> 高音,快速播放

AVAudioRecorder -> 正常,符合预期

使用 Apple 的耳机麦克风:

installTap -> 正常,如预期

AVAudioRecorder -> 正常,符合预期

知道为什么会这样吗?如果 AVAudioRecorder 能够按预期录制蓝牙输入,为什么我在通过 installTap 录制时得到高音调、快速播放?

installTap:

let format = mixer.outputFormat(forBus: 0)

let _bufferSize : AVAudioFrameCount = 4096

mixer.installTap(onBus: 0, bufferSize: _bufferSize, format: format) { 
(buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
        try self.outputFile.write(from: buffer)
}

输出文件:

try self.outputFile = AVAudioFile(forWriting: outputFile, settings: self._settings)

_设置:

let _settings = [
    AVLinearPCMIsFloatKey: 1,
    AVLinearPCMIsNonInterleaved: 1,
    AVFormatIDKey: Int(kAudioFormatLinearPCM),
    AVSampleRateKey: 44100,
    AVNumberOfChannelsKey: 2,
    AVLinearPCMBitDepthKey: 32,
    AVLinearPCMIsBigEndianKey: 0,
    AVEncoderAudioQualityKey: AVAudioQuality.low.rawValue
]

问题已解决。

事实证明,蓝牙麦克风的采样率设置为 8000 kHz,因此声音快速、高亢。这里的问题是,我们无法设置输入的设置。

为了解决这个问题,我不得不在输入节点和输出节点之间插入一个新节点,将新节点的采样率设置为 44,100 kHz,然后点击该新节点而不是主节点。

// our new node
var k44mixer = AVAudioMixerNode()

// the input node, which is currently the bluetooth mic
let input = engine.inputNode!
let inputFormat = input.inputFormat(forBus: 0)

// format for the new node
let k44format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 44100, channels: 2, interleaved: false)

// attach the new node to the audio engine
engine.attach(self.k44mixer)

// connect input to the new node, using the input's format
engine.connect(input, to: self.k44mixer, format: inputFormat)
// connect the new node to the output node
engine.connect(self.k44mixer, to: engine.outputNode, format: k44format)

// tap on the new node
self.k44mixer.installTap(onBus: 0, bufferSize: 1024, format: self.k44mixer.outputFormat(forBus: 0), block:
        { (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in

            print(NSString(string: "writing"))
            do {
                try self.outputFile.write(from: buffer)
            }
            catch {
                print(NSString(string: "Write failed"));
            }
    })

希望这对那里的任何人都有帮助。这让我挠头了一个多星期!干杯!