这个异常通常是由于音频引擎与硬件不兼容的采样率所导致的。解决方法是在启动 AVAudioEngine 之前设置正确的采样率,以确保音频引擎和硬件的采样率一致。以下是一个示例代码:
let engine = AVAudioEngine()
let mixer = engine.mainMixerNode
let input = engine.inputNode
// 设置采样率
let desiredSampleRate: Double = 44100.0
let inputFormat = input.inputFormat(forBus: 0)
let outputFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: desiredSampleRate, channels: 1, interleaved: false)
if let inputFormat = inputFormat, let outputFormat = outputFormat, let converter = AVAudioConverter(from: inputFormat, to: outputFormat) {
input.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { (buffer: AVAudioPCMBuffer, time: AVAudioTime) in
let convertedBuffer = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: AVAudioFrameCount(outputFormat.sampleRate * buffer.frameLength / inputFormat.sampleRate))!
var error: NSError?
let inputBlock: AVAudioConverterInputBlock = { (inNumPackets, outStatus) -> AVAudioBuffer? in
outStatus.pointee = AVAudioConverterInputStatus.haveData
return buffer
}
converter.convert(to: convertedBuffer, error: &error, withInputFrom: inputBlock)
mixer.ensureFormat(outputFormat)
mixer.installTap(onBus: 0, bufferSize: 4096, format: outputFormat) { (buffer: AVAudioPCMBuffer, time: AVAudioTime) in
// 处理音频数据
}
}
}
try engine.start()