I have an AVAudioRecorder that records audio and a music track playing while recording. When I record without headphones/earphones, the music playing gets picked up by the mic, even though I have it playing at a very low volume.
Can I somehow make the recorder ignore the music playing?
func startRecordingAudio() {
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
audioFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("audioRecorderTemp\(Date().timeIntervalSince1970)").appendingPathExtension("m4a")
do {
audioRecorder = try AVAudioRecorder(url: audioFileURL!, settings: settings)
audioRecorder?.record()
} catch {
finishRecordingAudio(success: false)
}
}
private func handleAudioSessionCategory(areHeadphonesConnected: Bool) {
if areHeadphonesConnected {
try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording)
} else {
try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .mixWithOthers, .allowBluetooth])
}
try? AVAudioSession.sharedInstance().setActive(true)
}
The issue you're facing is because you're using the .mixWithOthers option in the audio session category. This option allows audio from other apps, such as music playing in the background, to be mixed with your app's audio. If you want to prevent the music from being picked up by the microphone while recording, you should remove the .mixWithOthers option.