在 WatchOS 上使用 AVAudioEngine 录制时防止播放

Preventing playback while recording using AVAudioEngine on WatchOS

我在 iOS 中使用 AVAudioEngine 从麦克风收集 PCM 数据并且工作正常,但是当我尝试将项目移动到 WatchOS 时,我在录音时得到了反馈。录音时如何停止扬声器的播放?

var audioEngine = AVAudioEngine()

try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

let input = audioEngine.inputNode
let format = input.inputFormat(forBus: 0)

audioEngine.connect(input, to: audioEngine.mainMixerNode, format: format)

try! audioEngine.start()
let mixer = audioEngine.mainMixerNode

let format = mixer.outputFormat(forBus: 0)
let sampleRate = format.sampleRate
let fft_size = 2048

mixer.installTap(onBus: 0, bufferSize: UInt32(fft_size), format: format, 
            block: {(buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
    // Processing
}

对于遇到此问题的任何其他人,我通过移除从 inputNode 到 mainMixerNode 的连接来修复它,并将水龙头直接安装在 inputNode 上。在我猜测之前我这样做的方式创建了一个反馈循环,它正在播放它正在录制的内容。不确定为什么这只发生在 WatchOS 而不是 iPhone... 也许它是从耳机而不是麦克风旁边的扬声器播放的。固定码:

var audioEngine = AVAudioEngine()

try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

try! audioEngine.start()
let input = audioEngine.inputNode

let format = mixer.outputFormat(forBus: 0)
let sampleRate = format.sampleRate
let fft_size = 2048

input.installTap(onBus: 0, bufferSize: UInt32(fft_size), format: format, 
            block: {(buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
    // Processing
}